Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good concurrency example of Java vs. Clojure

Clojure is said to be a language that makes multi-thread programming easier.

From the Clojure.org website:

Clojure simplifies multi-threaded programming in several ways.

Now I'm looking for a non-trivial problem solved in Java and in Clojure so I can compare/contrast their simplicity. Anyone?

like image 755
Michiel Borkent Avatar asked May 26 '10 17:05

Michiel Borkent


1 Answers

I'd suggest also looking at Christophe Grand's thread safe blocking queue; it's less than 20 lines, but packs a lot of functionality, and in my opinion demonstrates expert use of some of Clojure's concurrency features, immutability, atoms, and lazy sequences.

Consider that the Java alternative java.util.concurrent.LinkedBlockingQueue is 842 lines of subtle (arguably complex) commented code, and you begin to understand how Clojure really does deliver on its concurrency promise; significantly raising the level of abstraction and delivering a correct implementation with approximately 10-20x less code.

You'll also notice that the when reading the Java code it is really hard to see the forest for the trees... If you were given it could you be sure of its correctness by looking at it? Also bear in mind that this code was written by Doug Lea (arguably the foremost expert on Java Concurrency) and is for java highly readable; I very much doubt I could write readable performant code such as this in Java quickly and be sure of its correctness.

Contrast this to the Clojure version and once familiar with the basics of Clojure it's easy to tease apart and understand how it works... Within 20 minutes I was able to understand every line of the implementation, and be sure of its correctness. And now that I'm far more familiar with Clojure's idioms and FP, I'd guess this would now take me closer to 5 minutes. I'd also probably be able to write "correct" code like this in Clojure in hours or minutes.

Christophes clojure wrapper of the above java class is also instructive as it shares the same functional interface as the first version.

like image 63
Rick Moynihan Avatar answered Oct 04 '22 19:10

Rick Moynihan