Saturday, 11 August 2012

delays, futures and promise

Delay

Delay is a concurrency function that delays the execution of some code until it is wanted.

(def s (delay (slurp "http://squidoop.blogspot.co.uk/")))
s
#<Delay@26e7127: :pending>
@s
"<!DOCTYPE html>\n<ht...

The code takes some time to execute on the first run, however once it is realized it is cached and the next dereference will be typical execution of any string.

Future

Future is an idiomatic way of creating execution for a new thread. Unlike native Java that requires a implmentation of Runnable for a piece of code, any function wrapped in a future will create and start a new thread but return execution immediately. You can use the ref of the future straight away however it may not be fully realized when you use it.

Unlike delays however, you can specify a timeout when dereferencing a future.

(deref (future (Thread/sleep 5000) :done!) 1000 :impatient!)
:impatient!

Promise

A promise is a completely uninitialised value. You promise to deliver a value to it some point in time later.

user=> (def p (promise))
#'user/p
user=> p
#<core$promise$reify__6153@5200089: :pending>
user=> (realized? p)
false
user=> (deliver p 42)
#<core$promise$reify__6153@5200089: 42>

Combining a future promise

(def a (promise))
(def b (promise))
(def c (promise))
(future (deliver c (+ @a @b)) (println "Delivery complete!"))

The future can't deliver because both a and b are unrealised promises.

(deliver a 15)
;= #<core$promise$reify__5727@56278e83: 15>
(deliver b 16)
; Delivery complete!
;= #<core$promise$reify__5727@47ef7de4: 16>
@c
;= 31

As soon as both promises have been delivered, the future stops being blocked and the delivery execution happens.

No comments:

Post a Comment