Tech behind Tech

Raw information. No finesse :)

Clojure futures – A Walkthrough

leave a comment »


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

Written by Siva Jagadeesan

July 14, 2010 at 4:22 am

Posted in Clojure

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 146 other followers

%d bloggers like this: