Friday, November 23, 2012

Use WeakHashMap as cache memory

When can we use WeakHashMap as cache memory? Having objects that are often reused and their creation is expensive, and there are too many of them to keep them all in memory.

SAMPLE CODE:
package com.jeeprojectsnippets.weakhashmap;

import java.util.WeakHashMap;

public class JeeProjectSnippets {

    public static void main(String[] args) {
  
        G33Value g33value = new G33Value();
        G33Key g33key = new G33Key();
        g33value.setStr("Value1");
        g33key.setKey(1);
        final WeakHashMap weakHashMap;
        weakHashMap = new WeakHashMap();
        final WeakHashMap weakHashMap2;
        weakHashMap2 = new WeakHashMap();
        final WeakHashMap weakHashMap3;
        weakHashMap3 = new WeakHashMap();
        weakHashMap.put(g33key, g33value);
        g33value.setStr("Value2");
        g33key.setKey(2);
        weakHashMap2.put(g33key, g33value);
        g33value.setStr("Value3");
        g33key.setKey(3);
        weakHashMap3.put(g33key, g33value);
        System.gc();
        System.out.println("weakHashMap.size() = " + weakHashMap.size());
        System.out.println("weakHashMap.get(g33key) = " + weakHashMap.get(g33key));
        g33key = null;
        int count = 0;
        while (0 != weakHashMap.size()) {
            ++count;
            System.gc();
        }
        System.out.println("weakHashMap.size() = " + weakHashMap.size());
        System.out.println("weakHashMap.get(g33key) = " + weakHashMap.get(g33key));
        System.out.println("Counter after exiting of the loop = " + count);
    }

    static class G33Key {
        private Integer key = null;

        public Integer getKey() {
            return key;
        }

        public void setKey(Integer key) {
            this.key = key;
        }
    }

    static class G33Value {
        private String str = null;

        public String getStr() {
            return str;
        }

        public void setStr(String str) {
            this.str = str;
        }
    }
}


RESULTS:
weakHashMap.size() = 1
weakHashMap.get(g33key) = pl.jeeprojectsnippets.weakhashmap.JeeProjectSnippets$G33Value@b8df17
weakHashMap.size() = 0
weakHashMap.get(g33key) = null
Counter after exiting of the loop = 6

Elements in a WeakHashMap can be reclaimed by the garbage collector if there are no other strong references to the object, this makes them useful for caches/lookup storage.
By te way, Java specifies five levels of reachability for objects in order of strongest-to-weakest:
*    Strongly Reachable
*    Softly Reachable
*    Weakly Reachable
*    Phantom Reachable
*    Unreachable


No comments: