Search code examples
javadictionarygarbage-collectionunmodifiable

Can Collections.unmodifiableMap retain the original map?


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?


Solution

  • 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 [...].