Clojure concurrency - part 1

May 11, 2010

Clojure has a very interesting set of features which promise to make handling concurrency easier compared to languages like Java. Persistent, immutable data structures, software transactional memory and (almost) pure functional programming are important aspects of the Clojure concurrency framework.

Explicit multithreading

It's easy to start a thread in Clojure:

(defn fun1 []
  (println "hello")

(defn fun2 []
  (println "world")

(.start (Thread. fun1))
(.start (Thread. fun2))

Run the above code as a script from the command line:

java -cp /path/to/clojure.jar clojure.main thread1.clj

Clojure functions can run as independent threads - we define two functions `fun1' which prints `hello' in a tight loop and another function `fun2' which prints `world' in a tight loop and run them as two independent threads.

Both `fun1' and `fun2' are performing the same action - print a message in a tight loop. It makes sense to have just one function which runs as two independent threads:

(defn fun1 [msg]
  (println msg)
  (recur msg))

(.start (Thread. #(fun1 "hello")))
(.start (Thread. #(fun1 "world")))

The real fun starts when the threads try to access/mutate global state; stay tuned!

[Go to Code Clojure home] [Follow me on Twitter] [Go to home]