Are the vals allocated inside defs automatically freed after the def returns?

def func = {
  val v1 = ...
  val v2 = ...
  val v3 = ...

The execution of func allocates v1, v2 and v3 on its own stack. So when func returns, are those allocations automatically cleared, without requiring v1, v2, v3 to be GC’d?

Those variables are put on the stack and will be cleared automatically when the method returns. But the objects they refer to are allocated on the heap and will eventually be cleared by the garbage collector. But even that is not guaranteed since your method returns v3 and that object may contain references to v1 and v2. As long as those objects are reachable they will not be cleared.

In theory it might be possible that an object that doesn’t escape the method gets allocated on the stack because of some JIT optimizations but I would never count on that. I’m not even sure that the standard Hotspot JVM ever does that.

1 Like

There is a difference between primitives and objects.

A primitive is an unboxed AnyVal. An AnyVal is unboxed if the type is known at declaration, either specified or inferred.

A primitive lives on the stack. There are no references to primitives, if you assign or return a primitive, it gets copied. A local primitive gets cleared when the method returns, but if you made copies of it they may continue to live elsewhere.

If the type is a parameter, it will be boxed, unless you use specialization. A boxed primitive is a primitive wrapped in an object.

An object is an AnyRef or a boxed AnyVal. An object lives on the heap, and if a method has a local object it means there is a reference to it on the stack. The reference itself, just like a primitive, gets cleared when the method returns, although if you assign or return the object, it means the reference gets copied.

If there are no more references to an object, it is eligible for collection, but there is no guarantee when that will happen.

Garbage collectors are usually optimized to categorize objects into old and new objects and try to collect new objects more frequently, because it is understood that many objects are not meant to live long.

1 Like