Thursday, May 24, 2007

A FutureResult based on FutureTask

This morning, I was looking within the java.util.concurrent package for something in the spirit of the FutureResult class in Doug Lea's util.concurrent library. Surprisingly enough, I did not find anything (did I miss something?).

So I cooked up my own version:

public class FutureResult<V> {
volatile V result;

volatile Exception problem;

final FutureTask<V> resultSyncer;

public FutureResult() {
Callable<V> resultReturner = new Callable<V>() {
public V call() throws Exception {
if (problem != null) {
throw problem;
} else {
return result;
resultSyncer = new FutureTask<V>(resultReturner);

public void set(V result) {
this.result = result;;

public void setException(Exception problem) {
this.problem = problem;;

public V get() throws InterruptedException, ExecutionException {
return resultSyncer.get();

The latest code for this class is available at:

Functionality of this nature can, of course, also be implemented with the help of plain-old wait/notify or condition variables. But this seemed like a neat way to accomplish what I wanted...


Anonymous said...

Hey Lalit,

This is Neeraj here. Thanks for the nice class.
Just wondering how we can use this class? I was thinking this class can work as a replacement of FutureTask ? Is my assumption correct?

Anonymous said...

java.util.concurrent.FutureTask does the same