On Tue, May 10, 2011 at 8:04 PM, Alan <[email protected]> wrote:
> (promise) hangs in 1.2, if you try to print it from the repl. There's
> a ticket somewhere for better handling of non-delivered promises.
Ah, damn. It should see if it's delivered or not and print
#<promise@5f18b> or similar in that case rather than try to print it.
Anyway, maybe this will come in handy:
(defn timeout-promise
"A promise with a timeout. When dereffed, returns the
delivered value if already delivered, otherwise blocks
until delivered or the deadline expires, whichever comes
first. Returns the delivered value if delivered in time and
if-timeout if the deadline expires first.
Ex.: user=> (def q (promise 1000 :timed-out))
user=>(do (future (Thread/sleep 900) (deliver q 42)) @q)
42
user=> (def q (promise 1000 :timed-out))
user=>(do (future (Thread/sleep 1100) (deliver q 42)) @q)
:timed-out"
[timeout-in-ms if-timeout]
(let [d (java.util.concurrent.CountDownLatch. 1)
v (atom nil)]
(reify
clojure.lang.IDeref
(deref [_] (if (.await d timeout-in-ms ms)
@v
if-timeout)).lang.IFn
(invoke [this x]
(locking d
(if (pos? (.getCount d))
(do (reset! v x)
(.countDown d)
this)
(throw (IllegalStateException.
"Multiple deliver calls to a promise"))))))))
Since the above code is derived from the existing implementation of
promise, it therefore automatically inherits the Clojure license terms
as the terms for its use, if I understand copyright law correctly.
The only changes from the implementation of promise are:
1. Docstring.
2. The two arguments.
3. Calls the await method of CountDownLatch that takes a timeout.
4. Conditions on the return value and returns if-timeout on failure.
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en