gpt4 book ai didi

java - 弱引用与设置为 Null

转载 作者:行者123 更新时间:2023-12-01 14:28:44 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Is there a practical use for weak references? [duplicate]

(9 个回答)


4年前关闭。




使用 Wea​​kReference 和将强引用类型设置为 null 有什么区别?

例如,在以下代码中,变量“test”是对“testString”的强引用。当我将“测试”设置为空时。不再有强引用,因此“testString”现在有资格进行 GC。因此,如果我可以简单地将对象引用“test”设置为等于 null,那么拥有 WeakReference Type 的意义何在?

class CacheTest {
private String test = "testString";

public void evictCache(){
test = null; // there is no longer a Strong reference to "testString"
System.gc(); //suggestion to JVM to trigger GC
}
}

为什么我要使用 Wea​​kReference ?
class CacheTest {
private String test = "testString";
private WeakReference<String> cache = new WeakReference<String>(test);

public void evictCache(){
test = null; // there is no longer a Strong reference to "testString"
System.gc(); //suggestion to JVM to trigger GC
}
}

最佳答案

在您的示例中,这两种情况没有区别。但是,请考虑以下与您类似的示例,其中存在区别:

class CacheTest {
private String test = "testString";
private String another = "testString";

public void evictCache(){
test = null; // this still doesn't remove "testString" from the string pool because there is another strong reference (another) to it.
System.gc(); //suggestion to JVM to trigger GC
}
}


class CacheTest {
private String test = "testString";
private WeakReference<String> cache = new WeakReference<String>(test);

public void evictCache(){
test = null; // this removes "testString" from the pool because there is no strong reference; there is a weak reference only.
System.gc(); //suggestion to JVM to trigger GC
}
}

关于java - 弱引用与设置为 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46452848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com