future - Clojure
Code
;; future.clj
(future
(println "This runs in background")
(Thread/sleep 1000)
(println "Done after 1 second"))
(let [f (future
(Thread/sleep 2000)
"Result")]
(println "Immediate return") ; Prints immediately
(println @f)) ; Blocks here for 2 seconds if needed
;;;;;;;;;;;;;
(def my-future (future (+ 1 2 3)))
;; Block until result is ready
(println @my-future) ; Prints: 6
;; Or with timeout (returns nil if not ready in 1000ms)
(deref my-future 1000 :timeout)
;;;;;;;;;;;;;
(do
(def my-future-3 (future (Thread/sleep 2000) (+ 1 2 3)))
;; Or with timeout (returns nil if not ready in 1000ms)
(deref my-future-3 100 :timeout))
;;;;;;;;;;;;;
(do
(def my-future-4 (future (Thread/sleep 20) (+ 1 2 3)))
;; Or with timeout (returns nil if not ready in 1000ms)
(deref my-future-4 100 :timeout))