Java Reference
In-Depth Information
It is very important to note that to take advantage of the garbage collector behavior with respect to soft references,
you must not keep a strong reference to the object. As long as you keep strong references to the object, the garbage
collector will not clear the soft references to it, even if the program is running low in memory. The garbage collector
clears the soft reference only if an object is softly reachable. Listing 11-5 shows the wrong use of soft references to
cache data.
Listing 11-5. An Incorrect Use of a Soft Reference
// WrongSoftRef.java
package com.jdojo.gc;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
public class WrongSoftRef {
public static void main(String[] args) {
// Create a big object with an id 101 for caching
BigObject bigObj = new BigObject(101);
// Wrap soft reference inside a soft reference
SoftReference<BigObject> sr = new SoftReference<BigObject>(bigObj);
// Let us try to create many big objects storing their
// references in an array list, just to use up big memory.
ArrayList<BigObject> bigList = new ArrayList<BigObject>();
long counter = 102;
while (true) {
bigList.add(new BigObject(counter++) );
}
}
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.jdojo.gc.BigObject.<init>(BigObject.java:7)
at com.jdojo.gc.WrongSoftRef.main(WrongSoftRef.java:20)
The intention of the programmer was to cache a big object with an id of 101 using a soft reference. If the program
runs low in memory, the cached big object with id 101 may be reclaimed. The while - loop inside the program
is trying to create many big objects to make the program run low in memory. The programmer is expecting that
when the program is executed, it should reclaim memory used by the big object with id 101, before throwing an
OutOfMemoryError .
The output shows that the program did not reclaim the memory used by the big object with id 101. Why did the
garbage collector not behave the way it was expected to behave? There was a mistake in the code for the WrongSoftRef
class. In fact, the big object with id 101 is strongly reachable because the bigObj reference to it is a strong reference.
You must set the bigObj reference variable to null to make it softly reachable. Listing 11-6 shows the correct use of
soft references. It is clear from the output that finalize() method for the big object with id 101 was called and it
was reclaimed before JVM threw an OutOfMemoryError . You still got an OutOfMemoryError because you are creating
many new objects inside a while-loop and all of them are strongly reachable from the array list. This proves the
point that soft references are cleared and the referents are reclaimed by the garbage collector before JVM throws an
OutOfMemoryError .
 
Search WWH ::




Custom Search