Hesey Hesey - 1 year ago 88
Java Question

What's the difference between Future and FutureTask in Java?

Since use

task and return a
, why need to use
to wrap
task and use the method
? I feel they both do the same thing.

Answer Source

In fact you are correct. The two approaches are identical. You generally don't need to wrap them yourself. If you are, you're likely duplicating the code in AbstractExecutorService:

 * Returns a <tt>RunnableFuture</tt> for the given callable task.
 * @param callable the callable task being wrapped
 * @return a <tt>RunnableFuture</tt> which when run will call the
 * underlying callable and which, as a <tt>Future</tt>, will yield
 * the callable's result as its result and provide for
 * cancellation of the underlying task.
 * @since 1.6
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
    return new FutureTask<T>(callable);

The only difference between Future and RunnableFuture, is the run() method:

 * A {@link Future} that is {@link Runnable}. Successful execution of
 * the <tt>run</tt> method causes completion of the <tt>Future</tt>
 * and allows access to its results.
 * @see FutureTask
 * @see Executor
 * @since 1.6
 * @author Doug Lea
 * @param <V> The result type returned by this Future's <tt>get</tt> method
public interface RunnableFuture<V> extends Runnable, Future<V> {
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
    void run();

A good reason to let the Executor construct the FutureTask for you is to ensure that there is no possible way more than one reference exists to the FutureTask instance. That is, the Executor owns this instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download