为什么垃圾回收【garbage collection】速度这么快?

bigbro001 bigbro001 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
下面这个测试程序,用来测试垃圾回收的速度,为什么在电脑上执行时,得到的输出是:
This object is uncollected!
It works!
这个结果说明gc()方法一执行,String对象马上就被回收了,为什么会这么快?更奇怪的是,有的人电脑上测试的结果却是:
This object is uncollected!
This object is uncollected!
This object is uncollected!
It works!
为什么会不一样呢?哪位前辈能给点提示?


import java.lang.ref.*;

public class Test
{
public static void main(String[] args)
{
String a = new String("This object is uncollected!");
WeakReference b = new WeakReference(a);
System.out.println(b.get());
//Remove strong reference to the String
a = null;
//Call garbage collector...
System.gc();
//Shouldn't the String be finalized?
if(b.get() == null)
System.out.println("It works!");
else // This is the condition that is executed
System.out.println(b.get());
System.exit(0);
}
}
...全文

相关推荐

评论 15
收藏 已收藏
分享
返回顶部
bigbro001
Java SE 62,621 成员 307,251 内容