Sunday 27 March 2016

Weak reference

What is weak reference?

To understand weak reference, first look at strong reference.

String s = new String("hello world");

This is strong reference. Only when s becomes null will the object 'new String("hello world")' become eligible for garbage collection.

 
Map strongMap = new HashMap();
Cat key = new Cat();
Object value = new Object();
strongMap.put(key, value);
key = null;
value = null;

The key in the map is also strong reference. Even though the key variable is set to null, the 'new Cat()' object cannot be garbage collected.
 
Map weakMap = new WeakHashMap();
Cat key = new Cat();
Object value = new Object();
weakMap.put(key, value);
key = null;
value = null;

Now that we put the key/value pair into a WeakHashMap, the 'new Cat()' object does become garbage collected once the key is set to null.

Here is a complete program to illustrate the difference.

First a utility class
 
private static class MyKey {
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("Gabage collected");
    }
}

StrongMap
public static void main(String[] args) {
    Map<MyKey, Object> strongMap = new HashMap<MyKey, Object>();
    for (int i = 0; i < 1000; i++){
       for (int j=0; j < 10000; j++){
            MyKey key = new MyKey();
            Object value = new Object();
            strongMap.put(key, value);
        }
    }
}
Output is OutOfMemory error

WeakMap
public static void main(String[] args) {
    Map<MyKey, Object> weakMap = new WeakHashMap<MyKey, Object>();
    for (int i = 0; i < 1000; i++){
       for (int j=0; j < 10000; j++){
            MyKey key = new MyKey();
            Object value = new Object();
            weakMap.put(key, value);
        }
    }
}

Output is tons of "Gabage collected" message and you don't see an OutOfMemory error.

No comments:

Post a Comment