There are two approaches to submitting and polling task for result
FutureTask futureTask = new FutureTask<String>(callable);
Use combination of Callable
and Future
and submit on ExecutorService
. Retrieve result using future.get()
.
Future future = service.submit(callable);
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 ?
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;
}