garbage collect objects after lazy values have been calculated
garbage-collection, lazy-evaluation, scala
Solution
You just need a little bit more tooling:
class Item(dataString: String) {
private var storedData = dataString
lazy val data = {
val temp = parse(storedData)
storedData = null
temp
}
}
An extra reference to `dataString` is not kept because you never refer to it outside of the constructor (which sets `storedData`), and the reference you store in `storedData` is nulled out once you use it, so the string is then free to be GCed.
Problem
in my current project I am processing a quite big amount of data and the processing of the data should be both memory efficient and computationally performant. Every item has some meta-data that can be read very fast and is almost always interesting. Additionally to that every item has the actual data that is comparatively rarely read but the reading and especially the parsing is very time consuming. Therefore it seams natural that the parsing of the data should only be done if it is actually requested. For that purpose I was thinking of lazy values: ``` class Item(metaData: MetaData, dataString: String) { lazy val data = parse(dataString) } ``` Now the data is only parsed if it is actually requested. The problem is now, that the dataString and the parsed data is kept in memory. As far as I can see, "dataString" cannot be accessed anymore as soon as "data" has been called (or is there?) and it can therefore be garbage collected. Unfortunately this seams not to happend. Is there a way to solve the problem in a different way or to give the garbage collector a hint to garbage collect the dataString here?