Future and FutureTask

Futures and FutureTasks are a great way to represent the result of an operation that is running on a thread. It also provides facilities like future.get() that is blocking while the Future operation is not yet complete.

Submitting a Callable (that defers from Runnable in that it returns a value and can throw exceptions as opposed to Runnable) forces the Executor to return back a Future. This is very useful technique for all those cases where we have expensive operations and the sooner we start them the better. On the other end when we invoke future.get() this operation blocks until we get a result back from the operation. For most of our purposes it is safe to assume the result of our operation to be represented by a Future that when it completes it is notifying us.

We can create a Future:

final Future future = Executors.newCachedThreadPool().submit(ourCallable);

or alternatively a FutureTask:

FutureTask<Callable> future = new FutureTask(ourCallable);
Thread thread = new Thread(futureTask);

On the other end we can expect the result of our expensive operation as follows:

Object result = future.get();