Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding Clojure futures

Tags:

clojure

future

I am trying to understand Clojure futures, and I've seen examples from the common Clojure books out there, and there are examples where futures are used for parallel computations (which seems to makes sense).

However, I am hoping someone can explain the behavior of a simple example adapted from O'Reilly's Programming Clojure book.

(def long-calculation (future (apply + (range 1e8))))

When I try to dereference this, by doing

(time @long-calculation)

It returns the correct result (4999999950000000), but almost instantly (in 0.045 msecs) on my machine.

But when I call the actual function, like so

(time (apply + (range 1e8)))

I get the correct result as well, but the time taken is much larger (~ 5000 msecs).

When I dereference the future, my understanding is that a new thread is created on which the expression is evaluated - in which case I would expect it to take around 5000 msec as well.

How come the dereferenced future returns the correct result so quickly?

like image 663
endbegin Avatar asked May 14 '12 03:05

endbegin


1 Answers

The calculation in a future starts as soon as you create the future (in a separate thread). In your case, the calculation starts as soon as you execute (def long-calculation ....)

Dereferencing will do one of two things:

  • If the future has not completed, block until it completes and then return the value (this could take an arbitrary amount of time, or even never complete if the future fails to terminate)
  • If the future has completed, return the result. This is almost instantaneous (which is why you are seeing very fast dereference returns)

You can see the effect by comparing the following:

;; dereference before future completes
(let [f (future (Thread/sleep 1000))]
  (time @f))
=> "Elapsed time: 999.46176 msecs"

;; dereference after future completes
(let [f (future (Thread/sleep 1000))]
  (Thread/sleep 2000)
  (time @f))
=> "Elapsed time: 0.039598 msecs"
like image 172
mikera Avatar answered Oct 13 '22 01:10

mikera