Fire and forget with java.util.concurrent

19.6k views Asked by At

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.

2

There are 2 answers

3
Sotirios Delimanolis On BEST ANSWER

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

0
leoismyname On

dont need the future object if you have to forget it i.e. dont care about the future of the thread. :)

ExecutorService executor = Executors.newSingleThreadExecutor();

public void push(Callable<Boolean> task) {
   executor.submit(task);
}

or if you need to use future some time later than :-

ExecutorService executor = Executors.newSingleThreadExecutor();

public void push(Callable<Boolean> task) {
   someCollection.add(executor.submit(task)); // use futures later
}

or just use execute from Executor and pass Runnable, if you dont intent to get the future at all.

ExecutorService executor = Executors.newSingleThreadExecutor();

public void push(Runnable task) {
   executor.execute(task);
}

// execute will invoke default exceptional handler in case of exception, that can be lost in case if you dont get hold of futures in submit method.