Search code examples
javajava.util.concurrentfire-and-forget

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.


Solution

  • 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().