All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jtrim2.executor.SyncNonRecursiveTaskExecutor Maven / Gradle / Ivy

There is a newer version: 2.0.7
Show newest version
package org.jtrim2.executor;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.jtrim2.cancel.CancellationToken;

final class SyncNonRecursiveTaskExecutor implements TaskExecutor {
    private final ThreadLocal> taskQueueRef;

    public SyncNonRecursiveTaskExecutor() {
        this.taskQueueRef = new ThreadLocal<>();
    }

    @Override
    public  CompletionStage executeFunction(
            CancellationToken cancelToken,
            CancelableFunction function) {

        CompletableFuture future = new CompletableFuture<>();
        execute(() -> CancelableTasks.complete(cancelToken, function, future));
        return future;
    }

    @Override
    public void execute(Runnable command) {
        Deque taskQueue = taskQueueRef.get();
        if (taskQueue == null) {
            taskQueue = new ArrayDeque<>();
            taskQueueRef.set(taskQueue);
            try {
                for (Runnable nextTask = command; nextTask != null; nextTask = taskQueue.pollFirst()) {
                    CancelableTasks.executeAndLogError(nextTask);
                }
            } finally {
                taskQueueRef.remove();
            }
        } else {
            taskQueue.addLast(command);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy