Aayush: weblog

Java Concurrency Utilities (Part-01): Callable, Future and FutureTask

Posted by Aayush on September 25, 2011


In this post, I will demonstrate through a very simple program the usage of the Callable, Future and FutureTask utilities. These utilities are present in the java.util.concurrent package.

However, before we come to the actual code – it is important to understand the use-cases behind the need for these utilities.

The use-case for having a Callable interface:

Sometimes, in our applications – we feel the need for our worker threads to have a return value. Doing so with usual threads is not possible, as the run() method does not have a return type.

In such cases, we can create a class which implements the Callable “type” and pass the instance of that class  to the in-built java thread pool.

The class which implements callable, is executed in a thread inside the Executor, and the return value of the “callable” is made available once the thread’s execution completes.

The use-case for Future and FutureTask:

It is often seen, that while designing APIs (being exposed to 3rd party applications), developers may provide API variants which expose a “synchronous” behavior as well as an option of “asynchronous” behavior, as viewed from the 3rd party application.

The processing for each incoming API call may happen in a worker thread, which in turn exchanges data over the network (or does some file I/O etc), and then a return value needs to be presented (think Callable), which has to be sent back to the API caller.

Hence, for the API caller, it seems that the invocation was synchronous. However, under the hood – the API spawns a worker thread, which is executed asynchronously by a thread pool and returns a value at some point in the “future”, when the processing is done.

In such cases, the concepts around Future and Future Task become important and come in handy for developers.

One of the practical usages of Future utilities can be from a protocol stack perspective – where the client sends a message through the stack. The stack sends the message over the network in a request submitter thread, receives a response “in the future” in a response listener thread and then this response is returned back to the caller thread.

The request submitter thread and the response receiver thread can communicate through an “Exchanger” concurrency utility of Java -  (http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Exchanger.html). However, this is a story for another time.

The example below is not that complex ! It only introduces these utilities.

Both these use-cases are illustrated below in the form of code snippets:

Code Snippet – Demonstrating Callable, Future and Future Task:

The main class – where we do all the stuff:

package org.demo.java.future;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * 
 * @author aayush.bhatnagar
 * 
 * Demo for Callable, Future and FutureTask.
 *
 */
public class FutureDemo 
{
 // This is our thread pool, which uses Java's internal thread pooling utilities.
 public static ExecutorService threadPool = Executors.newFixedThreadPool(3);

 public static void main (String[] args) throws InterruptedException, ExecutionException
 {
 // Demonstrating the Callable Interface usage.
 /*
 * The SomeTask.java class implements the Callable Interface, and is passed as an 
 * argument to the thread pool's submit method.
 * 
 * Please note, that the SomeTask class is not a Runnable type, but a Callable type.
 * 
 * Being a callable type means, that SomeTask can return a value once the task is executed by the
 * worker thread.
 */

 // The return value of the Callable, is stored here as a "Future" type.
 // In this particular example, we are expecting a String return type.
 Future<String> result = threadPool.submit(new SomeTask());
 // Getting the result as a Future type.
 String res = result.get();

 System.out.println("Result --> "+res);

 /*
 * A FutureTask class implements the Future interface. It provides for some
 * utility and control mechanisms on how the "Future" task would behave as follows - 
 */
 // Created a new future task with a Callable argument.
 FutureTask<String> task = new FutureTask<String>(new SomeTask());
 // Submitting to the thread pool..
 threadPool.submit(task);
 // Getting the result from the Future type (Future Task in this case).
 String res1 = task.get();

 System.out.println("Result --> "+res1);

 }

}

The SomeTask.java class which implements the Callable interface:

package org.demo.java.future;

import java.util.concurrent.Callable;

/**
 * 
 * @author aayush.bhatnagar
 * 
 * This class implements the Callable interface and
 * provides the implementation to the call ( ) method.
 *
 */
public class SomeTask implements Callable<String>
{

 @Override
 public String call() throws Exception 
 {
 // Here we do some dummy work.
 System.out.println("processing....");
 try {
 Thread.sleep(200L);
 } catch (InterruptedException e) {

 e.printStackTrace();
 }
 System.out.println("processing complete..exiting..");

 return "processing is complete";
 }

}
About these ads

One Response to “Java Concurrency Utilities (Part-01): Callable, Future and FutureTask”

  1. [...] WordPress.com « Java Concurrency Utilities (Part-01): Callable, Future and FutureTask [...]

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

 
Follow

Get every new post delivered to your Inbox.

Join 96 other followers

%d bloggers like this: