Please vote. Comments are encouraged!
- Yes, please teach this!
- No, I’m not interested.
I don’t know if this is covered by content elsewhere but I’d like to understand how Clojure’s various concurrency constructs interact with the JVM garbage collector.
My basic puzzle is this. On the one hand, objects in the JVM need to be referred to to stay alive. That is, if there is no reference to an object, then the JVM’s garbage collector can remove it at any time.
But on the other hand, many of clojure’s asynchronous API seem to be “fire and forget”. They allow you to request a block of code to be executed, but don’t necessarily require you to hold onto a reference to an object that keeps that block of code alive.
I can see three possibilities:
- Are we at risk of every piece of asynchronous code just spontaneously stopping when the objects underneath it are GCd?
- Or are we required to hold onto references to some kind of object associated with every task we request to be executed (e.g., the Thread object)?
- Or do parts of “the system”, whether it is the Java standard libraries or Clojure, take responsibility for holding a reference for us?
Some examples. If I do
(future (while true (Thread/sleep 10000) (println "hello")))
and I don’t hold onto the returned future, then who is holding onto a reference that keeps the running code from being GCd?
You can pose a similar question for
go, and even for tasks that I submit to a
ExecutorService. If I don’t hold onto the service, then are the unexecuted tasks at risk never of being executed because the executor could be GCd?
(Or alternatively, do isolated references cycles keep themselves alive forever, and in that case why am I not responsible for explicitly disposing of resources in all of the above examples?)
Basically, I’m trying to get a deeper understanding of what a developer’s responsibilities are in order to use Clojure’s asynchronous task constructs correctly, and it seems that understanding that requires understanding better how it hooks into the GC and Java’s concurrency constructs.