Future and FutureTask

Future and FutureTask in Java allows you to write asynchronous events, 
 
 
Callable is similar to Runnable, but it can return result unlike Runnable. Callable can be in one of three states: waiting to run, running, or completed.
 
 
Future : is a general concurrency abstraction, also known as a promise, which promises to return a result in future; i.e; a Future represents the result of an asynchronous computation.
 
FutureTask : It is an implementation of the Future interface. It is a cancellable asynchronous computation(methods are provided to start and cancel a computation). A FutureTask can be submitted to an Executor for execution as FutureTask implements Runnable. .You can also explicitly instantiate a FutureTask for a given Runnable or Callable.
 
 
You can get the result by calling the Future.get() method. If the task is completed, get returns the result immediately, and otherwise blocks until the task transitions to the completed state and then returns the result or throws an exception.
 
 
FutureTask is used by the Executor framework to represent asynchronous tasks, and can also be used to represent any potentially lengthy computation that can be started before the results are needed.
 
 
Future task
Class Preloader creates FutureTask by implementing the call()  method of the interface Callable.Two methods are created to start the thread and to get the ProductInfo object once the computation is completed; using the method future.get().
 
 
References:  
Tim Peierls; David Holmes; Joshua Bloch; Joseph Bowbeer; Doug Lea; Brian Goetz. Java Concurrency in Practice by Published by Addison-Wesley Professional, 2006

Add a comment