弱引用与设置为 Null

Weak Reference vs setting to Null

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

例如,在下面的代码中,变量 "test" 是对 "testString" 的强引用。当我将 "test" 设置为 null 时。不再有强引用,因此 "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 
  }
}

A​​ND

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 
  }
}