Back to Blog

Clojure for Beginners: Clojure future and promise — Simple Async with @deref and deliver

Celest KimCelest Kim

Video: Clojure future and promise — Simple Async with @deref and deliver | Episode 28 by CelesteAI

Watch full page →

Clojure future and promise — Simple Async with @deref and deliver

Two small primitives that cover the most common async patterns. `future` takes a body and runs it on a background thread — you get a reference back, and `@` deref returns the body's value when it's ready. `promise` is an empty cell that any thread can `deliver` a value into — `@` blocks until someone does. Both are one-shot: once set, the value is fixed.

Code

(ns app.core)

(defn slow-double
  "Fake slow computation — sleep 50*n ms, then return 2*n."
  [n]
  (Thread/sleep (* 50 n))
  (* 2 n))

(defn -main
  "Run with: clj -M:run"
  [& _]
  ;; ─── future: run something in the background, deref to collect ───
  (println "── futures ──")
  (let [f1 (future (slow-double 3))
        f2 (future (slow-double 1))
        f3 (future (slow-double 5))]
    (println "started three; main blocks on each @f")
    (println "f1 =" @f1 "  (was n=3)")
    (println "f2 =" @f2 "  (was n=1)")
    (println "f3 =" @f3 "  (was n=5)"))

  ;; ─── promise: a one-shot handoff between threads ───
  (println)
  (println "── promise ──")
  (let [p (promise)]
    (future
      (Thread/sleep 300)
      (deliver p :ready!))
    (println "main waiting on @p ...")
    (println "delivered:" @p))

  (shutdown-agents))

Key Points

Watch the video above for a full walkthrough — every keystroke is shown so you can code along.

Student code: GitHub