You're viewing version 1.2.0 of promise. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

promise

clojure.core

  • (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.

2 Examples top

  • 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
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:5501 top

(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"))))))))
Vars in clojure.core/promise: defn deref let locking pos? reify reset!
Used in 1 other vars deliver

Comments top

No comments for promise. Log in to add a comment.