我有一个简单的片段:
Integer integer = 2;
WeakReference<Integer> wi = new WeakReference<>(integer);
WeakReference<Integer> sr = new WeakReference<>(new Integer(3));
System.out.println(wi.get());
System.out.println(sr.get());
System.gc();
System.out.println("step 1 wi = " + wi.get());
System.out.println("step 1 sr =: " + sr.get());
integer = null;
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("step 1 wi = " + wi.get());
System.out.println("step 1 sr =: " + sr.get());
“System.gc()”调用应该强制回收所有弱引用,对,我什至等了 1 秒钟以确保 gc() 发生。但即使设置了“integer = null”,“wi”也拒绝为空。而 sr 在“System.gc()”之后为空。它打印:
2
3
step 1 wi = 2
step 1 sr =: null
step 1 wi = 2
step 1 sr =: null
我的问题:(1)wi和sr之间的核心区别是什么?(2)如何让jvm回收wi?
非常感谢。