Java Reference
In-Depth Information
Listing 11-6. A Correct Use of a Soft Reference
// CorrectSoftRef.java
package com.jdojo.gc;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
public class CorrectSoftRef {
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);
// Set bigObj to null, so the big object will be
// softly reachable and can be reclaimed, if necessary.
bigObj = null;
// 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++));
}
}
}
finalize() called for id:101
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.jdojo.gc.BigObject.<init>(BigObject.java:7)
at com.jdojo.gc.CorrectSoftRef.main(CorrectSoftRef.java:24)
Listing 11-7 illustrates how to use soft references to implement memory-sensitive caches.
Listing 11-7. Creating a Cache Using Soft References
// BigObjectCache.java
package com.jdojo.gc;
import java.lang.ref.SoftReference;
public class BigObjectCache {
private static SoftReference<BigObject>[] cache = new SoftReference[10];
public static BigObject getObjectById(int id) {
// Check for valid cache id
if (id < 0 || id >=cache.length) {
throw new IllegalArgumentException("Invalid id");
}
Search WWH ::




Custom Search