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);
thead.start();

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

Object result = future.get();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s