Scala: lazy vals, call by name, closures and memory leaks

I have a scala procedure that creates a large data structure using an even larger index in this process. Since I want to do this in one pass and not get bogged down in complex resolution, I use lazy vals as a result, initialized by expressions that may not be evaluated with the correct value (or any at all) at the time of component creation, but will do it as soon as the whole process assembly will be completed. This means that each component of the final result has a synthetic closure link with all of my index and, possibly, while any of them are still in memory, my index cannot be garbage collected. Obviously, I don’t want this - ideally, I would like to make a second pass through the structure to initialize the values ​​if necessary (and to ensure thatso that at this moment any errors are detected), and let the garbage collection index. I am currently passing an initialization expression by name through several functions and using it in a lazy val declaration equivalent to this:

class Component(init : =>Component) {
   lazy val property = init
}
...
new Component(index.get(parameters))

Is this sound? Will there be access to the synthetic initialization field by dereferencing once accessible to the lazy shaft? What if I want to use it in an initialization function, for example:

class Component(init : =>Component) {
   private def evaluate = init
   lazy val property = evaluate
}

Are there any rules to consider when programming with closure?

+4
source share
1 answer

The main problem that you describe, that the index cannot be garbage collected, is solved by putting the index in a mutable field that you are null out after creating the object.

, , , , (, , vals ), . sun.misc.Unsafe, . ( .)

, , : , , (!) , val, , , .

+4

All Articles