I’ve been considering switching the implementation of a compiler I’ve been working on to Clojure. From what I gather, Clojure JVM support multi-threading. Does Clojure JVM suport single-core or multi-core multi-threading? I had trouble arriving at a definitive answer for this.
Hi there, welcome to the community.
There are a few different JVM’s around including the ones shipped with Oracle Java and the OpenJDK and technically each JVM is free to implement the JVM in whatever way makes sense to the environment the JVM will execute in. That said, the Java Language Spec has the following to say about Threads:
… the Java Virtual Machine can support many threads of execution at once. These threads independently execute code that operates on values and objects residing in a shared main memory. Threads may be supported by having many hardware processors, by time-slicing a single hardware processor, or by time-slicing many hardware processors.
I think this answers your question, ie the JVM (and therefore clojure on the JVM) supports multi-threading on as many cores as the JVM has access to via the Operating System.
You get both. It’s possible to have lightweight threads (fibers/coroutines/green threads etc.) with libraries like core.async and limit yourself to a single os thread (or the only thread you have, in the case of clojurescript in the browser). Or you can multiplex them over a threadpool of OS threads, or mix-and-match. This is the approach clojure core.async takes (go routines are multiplexed over a user-configurable threadpool, and you can spawn dedicated threads as well).
You can also use existing java abstractions for OS threads, leverage fork/join, etc. clojure wraps os thread creation via
future and leverages a threadpool for handling
agent async processing. Clojure reducers (specifically
fold) leverage the fork/join implementation underneath.
Short answer is YES, Clojure lets you write multi-threaded, multi-core programs that can use all cores available, and this is first class, it’s not a niche or afterthought or need a library to do so thing, it’s the default behavior.
Other answers go into the details, but I felt maybe those details muddied the water.