Clojure futures – A Walkthrough
What is Future?
It is a simple mechanism to execute a snippet of code on a background thread.
How to use Future?
We can use Future in two ways.
1) Using macro “future”
(def f (future (prn "going to sleep...") (Thread/sleep 10000) (prn "slept good")))
2) Using function “future-call”
(defn long-process (Thread/sleep 10000)) (future-call long-process)
Under the shell both these ways are equivalent. The macro is syntax sugar and it gets converted to future-call.
Even though “long-process” function is put to sleep for 10 secs, it will return immediately. It returns a “future” object. We can use this object to inspect whether the function has been executed in background thread.
(future-done? f) (future-cancelled? f) (future-cancel f)
Limitations of Future?
As you known clojure comes with a bounded thread pool and unbounded thread pool. Mostly CPU bound operations should be using bounded thread pool and IO operations should be using unbound thread pool. Clojure Future uses unbounded thread pool, so it is good for IO operations but not for CPU bound operations. So for CPU bound operations Future might not be a good choice. But there is a open source project that helps to overcome this limitations. Check out http://github.com/amitrathore/medusa