When Java is providing the capabilities for concurrent programming, what are the major advantages in using Clojure (instead of Java)?
Because Clojure has interoperability with Java, there is a high dependency on the Java libraries rather than libraries written in Clojure. So, even though Clojure is a practical and functional language, most programs use Java libraries that tend to be less functional and have other side effects.
Haskell, Clojure, and Elixir/Erlang are especially well-suited to concurrent programming because they have strict rules governing where mutation can take place, making it more difficult to accidentally create a race condition. Rust is another option.
Clojure meets its goals by: embracing an industry-standard, open platform - the JVM; modernizing a venerable language - Lisp; fostering functional programming with immutable persistent data structures; and providing built-in concurrency support via software transactional memory and asynchronous agents.
In principle, Clojure can be just as fast as Java: both are compiled to Java bytecode instructions, which are executed by a Java Virtual Machine ... Clojure code will generally run slower than equiva- lent Java code. However, with some minor adjustments, Clojure performance can usually be brought near Java performance.
Clojure is designed for concurrency.
Clojure provides concurrency primitives at a higher level of abstraction than Java. Some of these are:
A Software Transactional Memory system for dealing with synchronous and coordinated changes to shared references. You can change several references as an atomic operation and you don't have to worry about what the other threads in your program are doing. Within your transaction you will always have a consistent view of the world.
An agent system for asynchronous change. This resembles message passing in Erlang.
Thread local changes to variables. These variables have a root binding which are shared by every thread in your program. However, when you re-bind a variable it will only be visible in that thread.
All these concurrency primitives are built on top of Clojures immutable data structures (i.e., lists, maps, vectors etc.). When you enter the world of mutable Java objects all of the primitives break down and you are back to locks and condition variables (which also can be used in clojure, when necessary).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With