views:

133

answers:

3

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.

+7  A: 

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.

Geoff Reedy
...which in many cases means: never
Kim
+5  A: 

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 }
}
Landei
+2  A: 

As the other user suggested, the object is eligible for collection only when its classloader can be collected. Unless you have a custom classloading scheme, this means dispatcher doesn't get collected, and the memory it needs never gets freed (assuming the object was initialized in the first place).

Other than manually resetting the dispatcher field to make the corresponding Dispatcher object eligible for collection, you can always automate this process by using a SoftReference.

axel22