what is the advantage of using FutureTask over Callable?

Amrish Pandey picture Amrish Pandey · Jun 22, 2015 · Viewed 15.9k times · Source

There are two approaches to submitting and polling task for result

FutureTask futureTask = new FutureTask<String>(callable);
  1. Use combination of Callable and Future and submit on ExecutorService. Retrieve result using future.get().

    Future future = service.submit(callable);
    
  2. Use FutureTask. This will wrap Callable and then retrieve result using FutureTask.

    service.execute(task);
    

What is the advantage of using FutureTask over Callable + Future combination ?

Answer

OldCurmudgeon picture OldCurmudgeon · Jun 22, 2015

Almost certainly none at all. A quick browse on GrepCode of the AbstractExecutorService shows each of these methods are simply helper methods that ultimately wrap the Callable/Runnable in a Future for you.

protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
    return new FutureTask<T>(runnable, value);
}

protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
    return new FutureTask<T>(callable);
}

public Future<?> submit(Runnable task) {
    // ...
    RunnableFuture<Object> ftask = newTaskFor(task, null);
    execute(ftask);
    return ftask;
}

public <T> Future<T> submit(Runnable task, T result) {
    // ...
    RunnableFuture<T> ftask = newTaskFor(task, result);
    execute(ftask);
    return ftask;
}

public <T> Future<T> submit(Callable<T> task) {
    // ...
    RunnableFuture<T> ftask = newTaskFor(task);
    execute(ftask);
    return ftask;
}