Tuesday 4 March 2014

WeakHashMap Demo

package com.core.java;

import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;

public class WeakHashMapDemo {

    public static void main(String[] args) {
/*        Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use.
        The garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries.       
        Collections.synchronizedMap(map) doesnt' not allow thread to remove entries from WeakHashMap.*/
       
        Map map =  new WeakHashMap();
        //Map map =  Collections.synchronizedMap(new WeakHashMap());
        Data someDataObject = new Data("foo");
        Data1 someDataObject1 = new Data1("foo");
        map.put(someDataObject, "");
        map.put(someDataObject1, "");
        System.out.println("map contains someDataObject ? " + map.containsKey(someDataObject));

        // make someDataObject elligible for garbage collection...
        someDataObject = null;

        for (int i = 0; i < 1000000; i++) {
            if (map.size() != 1) {
                System.out.println("At iteration " + i + " the map still holds the reference on someDataObject ::"+map.size());
            } else {
                System.out.println("somDataObject has finally been garbage collected at iteration " + i + ", hence the map is now empty ::"+map.size());
                break;
            }
        }
    }
}
class Data {
    String value;
    Data(String value) {
        this.value = value;
    }
}
class Data1 {
    String value;
    Data1(String value) {
        this.value = value;
    }
}


output:

At iteration 869 the map still holds the reference on someDataObject ::2
At iteration 870 the map still holds the reference on someDataObject ::2
At iteration 871 the map still holds the reference on someDataObject ::2
At iteration 872 the map still holds the reference on someDataObject ::2
somDataObject has finally been garbage collected at iteration 873, hence the map is now empty ::1

No comments:

Post a Comment