Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire and forget with java.util.concurrent

How to go about implementing a "fire and forget" behavior with java.util.concurrency? I tried:

ExecutorService executor = Executors.newSingleThreadExecutor();

public void push(Callable<Boolean> task) {
    Future<Boolean> future = executor.submit(task);
    future.get(timeout, timeoutUnit);
}

but the get() is blocking until completion. The push() caller is not interested in the result of the task.

like image 810
Philippe Blayo Avatar asked Dec 04 '22 09:12

Philippe Blayo


1 Answers

Don't call get(). submit() is enough to start the Callable in a Thread. You can pass around the Future and call its get() when you are ready to get the result (if ever).

The Javadoc states

Submits a value-returning task for execution and returns a Future representing the pending results of the task. The Future's get method will return the task's result upon successful completion.

If you would like to immediately block waiting for a task, you can use constructions of the form result = exec.submit(aCallable).get();

So just don't call get().

like image 70
Sotirios Delimanolis Avatar answered Dec 24 '22 03:12

Sotirios Delimanolis