What does FutureTask wrapper offer over simple Callable/Runnables? I've seen some people using futures that way, but I am not sure what it really adds to the game.
Callable<Integer> myComputation = () -> {return 0;};
FutureTask<Integer> task = new FutureTask<Integer>(myComputation);
//Why this...
Executors.newSingleThreadExecutor().execute(task);
task.get();
//...over the conventional approach?
Future<Integer> future = Executors.newSingleThreadExecutor().submit(myComputation);
future.get();
I see no benefits. The only difference in public interface is that FutureTask
implements RunnableFuture
which in addition to the Future
methods allows you to run the task via RunnableFuture.run()
method, but I doubt that you will need to run it directly.
The main purpose of using the FutureTask
class directly is the ability to subclass it providing custom implementation for some protected methods like done()
or setException()
. So it would make sense in the following piece of code:
Callable<Integer> myComputation = () -> {return 0;};
FutureTask<Integer> task = new FutureTask<Integer>(myComputation) {
@Override
protected void done() {
// some custom action on task completion
}
};