为什么 WeakReference 仍然 return 对象的值?
Why WeakReference still return the Object's Value?
我想知道如何使用 WeakReference
开发 android application.So 因为我在互联网上搜索了很多,所以我输入了以下代码:
{
String kk = "Test";
WeakReference<String> kkRef = new WeakReference<String>(kk);
System.out.println(kk);
System.out.println(kkRef.get());
kk = null;
System.gc();
System.out.println(kk);
System.out.println(kkRef.get());
}
假设 kk
对象符合 GC
,但在控制台输出中似乎 kkRef.get()
仍然 return "Test"
值应该 return null
正如我读到的 weakReference
那为什么没有 return null
?
首先,System.gc()
不一定执行完整的垃圾收集 运行,并且不能保证它会同步执行。因此,不能保证检测到所有弱持有的对象。
其次,字符串仍然被牢牢保留,因为它是您代码中的字符串文字。那永远不可能被垃圾收集,所以对它的 WeakReference
仍然是 return 字面量。
我想知道如何使用 WeakReference
开发 android application.So 因为我在互联网上搜索了很多,所以我输入了以下代码:
{
String kk = "Test";
WeakReference<String> kkRef = new WeakReference<String>(kk);
System.out.println(kk);
System.out.println(kkRef.get());
kk = null;
System.gc();
System.out.println(kk);
System.out.println(kkRef.get());
}
假设 kk
对象符合 GC
,但在控制台输出中似乎 kkRef.get()
仍然 return "Test"
值应该 return null
正如我读到的 weakReference
那为什么没有 return null
?
首先,System.gc()
不一定执行完整的垃圾收集 运行,并且不能保证它会同步执行。因此,不能保证检测到所有弱持有的对象。
其次,字符串仍然被牢牢保留,因为它是您代码中的字符串文字。那永远不可能被垃圾收集,所以对它的 WeakReference
仍然是 return 字面量。