1.3.0 permalink 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, unless the variant of deref with timeout is used. All
subsequent derefs will return the same delivered value without
blocking. See also - realized?.

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:6176 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, unless the variant of deref with timeout is used. All
  subsequent derefs will return the same delivered value without
  blocking. See also - realized?."
  {:added "1.1"
   :static true}
  []
  (let [d (java.util.concurrent.CountDownLatch. 1)
        v (atom d)]
    (reify 
     clojure.lang.IDeref
       (deref [_] (.await d) @v)
     clojure.lang.IBlockingDeref
       (deref
        [_ timeout-ms timeout-val]
        (if (.await d timeout-ms java.util.concurrent.TimeUnit/MILLISECONDS)
          @v
          timeout-val))  
     clojure.lang.IPending
      (isRealized [this]
       (zero? (.getCount d)))
     clojure.lang.IFn
     (invoke
      [this x]
      (when (and (pos? (.getCount d))
                 (compare-and-set! v d x))
        (.countDown d)
        this)))))
Vars in clojure.core/promise:
Used in 0 other vars

Comments top

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