Suresh Harikrishnan
D e c e m b e r 11 , 2 0 0 9 Episode 7

Concurrency, Time and Clojure
Have you ever wondered what concurrency and time related constructs your favorite programming language provides? I did, after watching this wonderful presentation by Rich Hickey: Java supports concurrency using its Threads library. There are a few constructs supporting multi-threading, but mostly to ensure you play safe when using threads. These constructs are available to protect the mutable state in objects. And Java's notion of time is limited to a few (rather awful) classes in its library. Rich Hickey uses the example of athletes running a race to show the problem of concurrency with most languages in use today. If you want to know who is leading a race, you don't ask the athletes to stop running. The athletes keep running as you notice the current standings. Simply put, Java and other popular languages presumes single shared timeline. Compare this with Clojure. Clojure's approach to concurrency is provided by 2 distinct features - functional approach to its data structures and different styles of concurrency constructs. It's pure functions are time independent, in other words, side effects free. Clojure data structures are immutable, but persistent. It differentiates "Value" from the notion of identity. Most OO languages treat them as one - an Account object could have no balance, and then when you deposit something into this account, it takes a positive balance. Clojure on the other hand would differentiate the account identity from the actual balance in that account.

Only the references are mutable. And Clojure supports 3 types of mutable references: • Synchronous coordinated changes between threads using refs. ◦ Clojure uses STM for ref modifications. ◦ You need to be inside a transaction context to change refs • Asynchronous coordinated changes between threads using agents. ◦ Ala Actor models ◦ You pass a function to change the state of the agent • Isolate changes within a thread using vars. ◦ Equivalent to thread locals. Check out more about clojure at There is lot more to say about clojure, maybe later :)