Java Callable Future Example

Callable interface was added in Java 5 to achieve some limitation in existing Runnable interface. A Thread created by implementing the Runnable interface cannot returns a result when the thread terminates. As the return type of run() method in Runnable interface is void. To overcome this the Callable interface was introduced in Java where we can return a result when the thread terminates. Method signature that has to be overridden for implementing Callable is as following.

public Object call() throws Exception;

Another difference between the call() and run() method is call() is able to throw an Exception where run() cannot. The Java Callable interface uses Generics, so it can return any type of Object.

The Executor Framework has a submit() method. Using this we can executes callable threads in a Thread Pool. The Thread pool can be obtained as:

ExecutorService executor = Executors.newFixedThreadPool(10);

Then we cansubmit a task to it. The task is an implementation of Callable interface. Following is an example of Callable implementation.

Java Future : Java Callable tasks return java.util.concurrent.Future objects. Using this Java Future object, we can find out the status of the Callable task and get the returned Object. It provides a get() method that can wait for the Callable task to finish and then return the result. The Future interface also defines a cancel() method to cancel task. As discussed the get() is a blocking call and it blocks until computation is completed. There are also isDone() and isCancelled() methods to find out the current status of an associated Callable task.

Here is a example of Java Callable task , where we have 3 Array of Integer. Our goal is to add all the array elements and Get their SUM. The task is very straight forward. But we will use different callable tasks to add each array. And then collect all the results from each Callable task in corresponding Future Object. Follwoing is our Callable implementation to add each array.