Search code examples
scalagarbage-collectionakkaactorgarbage

Akka Actor message memory and Garbage Collection


Is the following statement correct: when an Actor receives a message, after completing the pattern-matched function, the message goes out of scope and the message is garbage collected?


Solution

  • On the JVM objects may be garbage collected when it is no longer strongly reachable, i.e. there is no chain of "normal" references via that it can be reached from some thread running in the JVM.

    So this means, the simple answer to your question is: no. You do not never know, when or even if the message will be garbage collected. What you know is that the reference that goes out of scope is deleted. However, this does not even mean that the message is no longer reachable. The object could still be referenced from some other actor.

    Typically, however, if a message is send and the sending actor keeps no reference to it, and the receiving actor removes its reference to it, it should be garbage collected quite soon. Messages are typically short-lived objects so most likely the object will not survive even one GC-cycle.