Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Clojure instead of Java for concurrent programming

When Java is providing the capabilities for concurrent programming, what are the major advantages in using Clojure (instead of Java)?

like image 777
John Jesudason Avatar asked Oct 15 '09 07:10

John Jesudason


People also ask

Is Clojure better than 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.

What is the best programming language for concurrency?

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.

What are the advantages of Clojure?

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.

Is Clojure faster than Java?

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.


1 Answers

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).

like image 181
Jonas Avatar answered Sep 19 '22 13:09

Jonas