5

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();
Whimusical
  • 6,401
  • 11
  • 62
  • 105
  • There are some more good insights on this question here: http://stackoverflow.com/questions/4956822/whats-the-difference-between-future-and-futuretask-in-java – Fritz Duchardt Nov 30 '15 at 10:17

1 Answers1

3

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
    }
};
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • 3
    Wrapping manually is required when you only have an `Executor` instead of `ExecutorService`. Or if you want to be able to cancel your own task from within the actual action. – Holger Nov 30 '15 at 09:54