Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are Scala objects garbage collected?

This question is about Scala objects, which are defined something like this:

object Pipeline {
   val dispatcher = new Dispatcher
}

I know that, in some circumstances, they are referred to as 'companion' objects, although I don't yet understand the distinction. Anyway, I want to know when they get garbage collected. So, in the above example, I'd like to know when the memory occupied by dispatcher is reclaimed, if ever.

like image 832
David Avatar asked Oct 18 '10 04:10

David


People also ask

Is Scala garbage collected?

Garbage collection is the responsibility of the JVM, not Scala. So the precise details depend on which JVM you're running. There is no defined time at which garbage collection is triggered; the JVM tries to do it when it is opportune or necessary.

What is garbage collection in Scala?

Garbage collection is the memory management process for objects in the heap. As objects are allocated to the heap, they run through a few collection phases – usually rather quickly as the majority of objects in the heap have short lifespans.

What triggers garbage collection?

When a JVM runs out of space in the storage heap and is unable to allocate any more objects (an allocation failure), a garbage collection is triggered. The Garbage Collector cleans up objects in the storage heap that are no longer being referenced by applications and frees some of the space.

Which objects are garbage collected?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object?


2 Answers

When compiled to jave bytecode companion objects are lazyily initialized static members. For most java implementations this means that they would be eligible for collection when the classloader loading the object is eligible for collection. It's really quite implementation dependent stuff though.

like image 74
Geoff Reedy Avatar answered Nov 23 '22 11:11

Geoff Reedy


The object Pipeline is always "reachable", and so is dispatcher (similar to a static field in Java), so my guess would be that it isn't garbage collected. If you want to control the life cycle of dispatcher, you could do something like

object Pipeline {
    var dispatcher = Some(new Dispatcher)
    def close() { dispatcher = None }
}
like image 29
Landei Avatar answered Nov 23 '22 12:11

Landei