Why you will love Clojure for concurrent programming

Java has one of the best libraries for cross-platform concurrent programming. Java Concurrency in Practice is a must-read for those who are really interested in the topic. The problem is that concurrency is hard, even for experienced programmers.

Two or more tasks are said to run concurrently when they are run at the same time on a CPU. The CPU can run only one of them at each moment, but each can take the CPU for some time and then leave it for the others ready to come back in the future.

As long as the tasks are independent (they don't have to send messages or share resources in order to complete themselves) no problem arises. However, inside an application, most of the time, this is not the case.

The easiest way for concurrent tasks to communicate is to share some memory locations. This approach is quite common but requires careful management of access to them.

The functional paradigm completely changed the approach to this problem. One of the main concepts in functional languages is immutability. When we are sure that some memory locations are not going to change, we can share them safely and everybody can access them. Assume that we received a reference to an array and we want to change a single value and send a reference to the new array. In most languages, we would have to create a copy of the array (because we assume we only share read-only variables), change the value and then send it, which is really bad for performance.

Clojure is a functional programming language that runs on the JVM. By default all variables are immutable and the standard library is designed to solve the problem we cited before really efficiently. We can take an object, change it and share a brand new copy in a really efficient way (we don't have to create a copy before).

There is no magic behind it, an array won't be a group of cell one next to the other in memory, it will be represented as a tree (but a really shallow one). However, when you interact with it, you won't notice it.

Moreover, it makes it really easy to interact with Java objects and it also implements many syntactic sugars to improve the readability of code. This is all built-in, it is a nice group of features.

As soon as the problem becomes more complex there are external libraries that implement modern patterns (for example, functions that work like go routines).