Alpha - subject to change.
Returns a promise object that can be read with deref/@, and set,
once only, with deliver. Calls to deref/@ prior to delivery will
block. All subsequent derefs will return the same delivered value
without blocking.
user=> (def x (promise)) #'user/x ;; Trying to deref at this point will make your repl wait forever user=> (deliver x 100) #<core$promise$reify__5534@4369a50b: 100> ;; the promise has been delivered, deref x will return immediately user=> @x 100
;; Create a promise user> (def p (promise)) #'user/p ; p is our promise ;; Check if was delivered/realized user> (realized? p) false ; No yet ;; Delivering the promise user> (deliver p 42) #<core$promise$reify__5727@47122d: 42> ;; Check again if it was delivered user> (realized? p) true ; Yes! ;; Deref to see what has been delivered user> @p 42 ;; Note that @ is shorthand for deref user> (deref p) 42
(defn promise
"Alpha - subject to change.
Returns a promise object that can be read with deref/@, and set,
once only, with deliver. Calls to deref/@ prior to delivery will
block. All subsequent derefs will return the same delivered value
without blocking."
{:added "1.1"}
[]
(let [d (java.util.concurrent.CountDownLatch. 1)
v (atom nil)]
(reify
clojure.lang.IDeref
(deref [_] (.await d) @v)
clojure.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"))))))))
Comments top
No comments for promise. Log in to add a comment.