0

I have a piece of code below:

class Util {
    private static final Map<String, String> MY_MAP;

    static {
        Map<String, String> tmpMap = new TreeMap<String, String>();
        tmpMap.put("key1", "val1");
        tmpMap.put("key2", "val2");
        tmpMap.put("key3", "val3");

        MY_MAP = Collections.unmodifiableMap(tmpMap);
    }

    public static String getVal(String key) {
        return MY_MAP.get(key);
    }
}

Can MY_MAP retain the tmpMap always? Or in other words, is it possible that the GC will recycle the tmpMap which makes the MY_MAP inaccessible?

injoy
  • 3,993
  • 10
  • 40
  • 69

2 Answers2

3

The returned Map is just a "view" which wraps around the Map passed in.

So yes, tmpMap will be retained as long as MY_MAP is alive. Since MY_MAP is a static final field, tmpMap will be retained basically forever.

unmodifiableMap:

Returns an unmodifiable view of the specified map. [...] Query operations on the returned map "read through" to the specified map [...].

Community
  • 1
  • 1
Radiodef
  • 37,180
  • 14
  • 90
  • 125
3

Or in other words, is it possible that the GC will recycle the tmpMap which makes the MY_MAP inaccessible?

No, never. MY_MAP has a (strong) reference to tmpMap, so it can't be collected.

In general, the GC will never do anything like this. You'll never see it working, except in special cases (WeakHashMap and similar).

maaartinus
  • 44,714
  • 32
  • 161
  • 320