Java Callable Future Example

Java concurrent API support Callable and Future interfaces to implement threads that can return a value. One simple use case for a Callable object is to return status (Success/ Failure) of thread execution to the invoking object. More practical use cases include perform number crunching operations simultaneously wherein partial results could be return back to the parent object. This article provides a quick introduction to Callable and Future interfaces with an example.

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. Main difference is that Runnable object cannot return a value whereas a Callable can return.

Future interface is the value returned by a Callable object. We need a ExecutorService object to execute a Callable task. Refer to this link for more information on ExecutorService. The submit() method on the executor object is used to execute the Callable tasks.

To read the return value from Future object get() API can be used. There are 2 flavors of get() API.

  • get() – Waits if necessary for the computation to complete, and then retrieves its result.
  • get(long timeout, TimeUnit) – Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

In this example we create a Callable task SumToN and we execute the task using an ExecutorService. Return value is captured using the Future object.

package com.sourcetricks.callable;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;public class CallableDemo {private static class SumToN implements Callable<Integer> {private int n;public SumToN(int n) {this.n = n;}@Overridepublic Integer call() throws Exception {int sum = 0;for ( int i = 0; i < n; i++ ) {sum += i;}return sum;}}public static void main(String[] args) {ExecutorService executor = Executors.newFixedThreadPool(2);Future<Integer> futureVal1 = executor.submit(new SumToN(100));Future<Integer> futureVal2 = executor.submit(new SumToN(1000));try {System.out.println(futureVal1.get());System.out.println(futureVal2.get(2000, TimeUnit.MILLISECONDS));} catch (InterruptedException | ExecutionException | TimeoutException e) {e.printStackTrace();}}}

This program produces the following output.


Read other concurrency tutorials from Java Tutorials page.