[concurrency-interest] Joining on multiple futures (ListenableFuture?)

Joe Bowbeer joe.bowbeer at gmail.com
Tue Dec 18 14:43:55 EST 2007

On Dec 18, 2007 10:54 AM, Rowlands, Ben (IT)
<Ben.Rowlands at morganstanley.com> wrote:
> Are there any utilities in j.u.c to help join on multiple futures? For
> example,
>  // returns when all futures complete or a future fails
>  join( Future... futures, long timeout, TimeUnit unit )
> A trivial implementation would loop through each future and call get().
> This would work, and we could keep track of the time spent waiting on
> each future to support a timeout.
> The main drawback of this technique is we only find out about a failed
> future after we've called get() on all previous futures. We'd like to
> learn about a failure as soon as possible to start recovery (if any
> futures fail we repeat the unit of work, so the sooner we can detect a
> failure the better). We cancel any pending futures before the repeat.
> Our alternative implementation uses polling by calling get() with a
> timeout of a few hundred ms and looping until all complete. This works
> but isn't terribly elegant, and has caused some problems with poorly
> implemented futures (the polling basically gets pushed down to the
> resource the future wraps, often a read on a TCP socket within the
> timeout).
> In our use-case, the futures are backed by tcp sockets (they hold the
> result of a tcp request). One solution might be support for
> "ListenableFutures" that notify a listener when they complete (or fail
> with an exception), allowing us to use a more efficient strategy to join
> on the futures. Something like:
>   interface ListenableFuture extends Future {
>     // register a listener to be called when this future is 'ready' (has
> a result or failed)
>     // if the future is already complete the callback is fired
> immediately
>     void registerListener( FutureListener listener );
>   }
>   interface FutureListener {
>     void ready( Future future );
>   }
> I'd guess there are other Futures that could support asynchronous
> notification on completion including async file IO.
> Are there any plans to support anything like this? Or have we missed
> something obvious? I came across a discussion back in 2003 related to
> this but it looks like the done() subclass hook that resulted is more
> for implementers of futures than consumers of the future(s).
>   http://osdir.com/ml/java.jsr.166-concurrency/2003-10/msg00001.html
> Thanks,
> Ben

You didn't mention ExecutorCompletionService.  You might find what you
need there.

Concerning listeners, one can override the done() completion hook to
implement observable FutureTask subclass that sends events to
listeners.  The new SwingWorker does this
(https://swingworker.dev.java.net/), and the SwingWorker in this
article enqueues a runnable event:



More information about the Concurrency-interest mailing list