This post originated from an RSS feed registered with Java Buzz
by Lalit Pant.
Original Post: A FutureResult based on FutureTask
Feed Title: All Things Runnable / Java
Feed URL: http://feeds.feedburner.com/lalitpant/java
Feed Description: Java related posts on Lalit Pant's Blog
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;
Exception problem;
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; resultSyncer.run(); }
public void setException(Exception problem) { this.problem = problem; resultSyncer.run(); }
public V get() throws InterruptedException, ExecutionException { return resultSyncer.get(); } }
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...