I had a test servlet running in Jetty embeded in a junit test, and I wanted the junit test to make a response to a remote service and wait for the remote service to POST a message to the jetty server. When the POST came in, I wanted the junit test to grab it and then compare the result.

So I wanted to use the Future class, but I didn’t have an Executor involved. That’s how you usually get and use a future — you give it a Runnable or Callable wrapped in a FutureTask, then wait for the executor to call run() or call().

Instead, I set up a FutureResult class. The name might not be just right, but the idea is that it wraps a FutureTask and a Callable, and then just sits there. When someone — maybe another thread — decides to pass in a value after all, then the class hands that value to the Callable object, and invokes run() on the FutureTask. So to the outside world, it looks like the Future has just come alive.

The usage is like this:

FutureResult shared = new FutureResult();

// in one thread...
Future future = shared.future();
future.get(); // blocks, but you can specify a timeout parameter

// in another thread...
shared.setValue("woo!"); // will cause the future to unblock and return that value immediately

And here’s the implementation. This is really rough. I could probably just write the internals of FutureResult directly, and not worry about the embedded Callable, but I wanted to use the work that’s already in the system. Also, I’m not sure FutureResult is the right name. It might be better to make FutureResult implement the Future interface and just delegate down all it’s calls to the Future object…. hm.

public class FutureResult<V> {

public final FutureTask future;

public V result;

public FutureResult() {

Callable callable = new Callable() {

public V call() throws Exception {
return result;


future = new FutureTask(callable);


public Future future() {
return this.future;

public void setResult(V value) {
result = value;


Leave a comment

Filed under design patterns, utility

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