09: Java FutureTask example

Java 5 introduced the concurrent package for more efficient multi-threading.

Q. What is the difference between Future and FutureTask in asynchronous processing?
A. Future is the interface and FutureTask is the base implementation of the Future with methods to start and cancel a computation. The FutureTask provides asynchronous computation with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed. The get method will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled.

Here is an example with 2 tasks. One is an internal short task that takes ~1 second. The second task is an external long running task taking 4 ~ 10 seconds. It is imperative that long running tasks need to have proper processing timeouts.

The output is

If you re-run it by uncommenting the last 2 lines in the TimeoutException catch block, you will get task2 cancelled.


Java Interview FAQs

800+ Java Interview Q&As

Top