使用WeakReference和将强引用类型设置为null有什么区别?
例如,在以下代码中,变量“test”是对“testString”的强引用。当我将“test”设置为null时,就不再有强引用,因此“testString”现在可以进行垃圾回收。因此,如果我只需将对象引用“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
}
}