使用WeakReference和将强引用类型设置为null有什么区别?
例如,在下面的代码中,变量“test”是对“testString”的强引用。当我将“test”设置为null时。不再有强参考,因此“testString”现在符合GC的条件。因此,如果我可以简单地将对象引用“test”设置为null,那么具有WeakReference类型的重点是什么?
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
}
}
为什么我要使用WeakReference?
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
}
}
答案 0 :(得分:2)
在您的示例中,两种情况之间没有区别。但是,请考虑以下与您的类似的示例:
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
}
}