首页   

WeakHashMap与String键

王侦  ·  · 4 年前
public class WeakHashMapStringKeyTest {
    public static void main(String[] args) {
        WeakHashMap<String, String> objectMap = new WeakHashMap<>();
        String k1 = new String("k1");
        String k2 = new String("k2");
        objectMap.put(k1, "v1");
        objectMap.put(k2, "v2");
        System.out.println(objectMap.get(k1));
        System.out.println(objectMap);
        System.out.println("before GC, size = " + objectMap.size());
        k1 = null;
        System.gc();
        System.runFinalization();
        System.out.println();
        System.out.println("after GC, size = " + objectMap.size());
        System.out.println(objectMap.get(k1));
        System.out.println(objectMap);

        System.out.println("=========================");
        WeakHashMap<String, String> constantMap = new WeakHashMap<>();
        String k3 = "k3";
        String k4 = "k4";
        constantMap.put(k3, "v3");
        constantMap.put(k4, "v4");
        System.out.println(constantMap.get(k3));
        System.out.println(constantMap);
        System.out.println("before GC, size = " + constantMap.size());
        k3 = null;
        System.gc();
        System.runFinalization();
        System.out.println();
        System.out.println("after GC, size = " + constantMap.size());
        System.out.println(constantMap.get(k3));
        System.out.println(constantMap.get("k3"));
        System.out.println(constantMap);
    }
}

结果:

v1
{k2=v2, k1=v1}
before GC, size = 2

after GC, size = 1
null
{k2=v2}
=========================
v3
{k4=v4, k3=v3}
before GC, size = 2

after GC, size = 2
null
v3
{k4=v4, k3=v3}

字符串常量放在常量池中,相当于k3引用的是常量池中的内容,所以WeakReference中的referent也引用的是常量池中内容。即使k3 = null,常量池中的对象也不会被回收。

推荐文章
YuLabSMU  ·  scholar包不再404了!  ·  2 年前  
© 2022 51好读