Re: Making one or more threads wait for another to produce a value
or fail
This message is in MIME format. The first part should be readable text,
while the remaining parts are likely unreadable without MIME-aware tools.
--232016332-2075174534-1306962513=:4421
Content-Type: TEXT/PLAIN; CHARSET=UTF-8; FORMAT=flowed
Content-Transfer-Encoding: 8BIT
Content-ID: <alpine.DEB.2.00.1106012208381.4421@urchin.earth.li>
On Tue, 31 May 2011, Deeyana wrote:
On Tue, 31 May 2011 16:46:55 +0100, Tom Anderson wrote:
On Tue, 31 May 2011, Peter Duniho wrote:
(Alternatively, you could provide a custom implementation of Future<V>
that doesn't wrap a Runnable like FutureTask<V>, letting your thread
continue even after delivering the Future<V>???but such an implementation
would be more complicated than just using the wait()/notifyAll()
pattern,
Not *that* much more complicated, i don't think. Both varieties of get
map on to calls to their corresponding variety of wait in a loop guarded
by a call to isDone, and isDone maps on to a check on whether the
verdict is delivered. cancel/isCancelled would require code over and
above the simplest wait/notify implentation, but not a lot.
The thing that bugs me is that if this is so simple, and as generally
useful as i think it is, why isn't it in the JDK already?
I don't know. But it is available in at least one other JVM language's
standard library: Clojure has functions called "promise" and "deliver"
for exactly this sort of scenario. Under the hood it combines a
CountDownLatch with a class instance variable to hold the result and
implements Clojure's IDeref interface. The Java equivalent would just be
some class Promise<T>
I assume you didn't see it, but shortly before you posted, i posted this:
http://urchin.earth.li/~twic/Code/Promise.java
Great minds think alike.
with internal value and CountDownLatch and deliver and get methods.
Deliver would decrement the CountDownLatch and set the value cell; get
would see if the CountDownLatch was zero, block if it wasn't, and return
the value cell's contents if it was. It would also throw
InterruptedException and maybe have a version of get accepting a
timeout.
I used wait/notify rather than a CountDownLatch, but that's more or less
exactly what my class does.
tom
--
You have to give up
--232016332-2075174534-1306962513=:4421--