弱引用 vs 设置为 Null

5

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

我不同意你所提到的问题范围非常广泛,这里我提出了一个非常明确的问题,并附上了一个示例。 - Shivam Sinha
@ShivamSinha 这个重复的答案和文档已经详细介绍了这一点。当您不介意将引用设置为空时,就不需要弱引用。弱引用的目的是让GC替你处理它,无需手动将其置空。这类似于“GC有什么意义,我可以在不再需要时自行释放资源”的概念。 - pvg
3
对于这种简单的情况,WeakReference 是过度的。如果您有一个更大的应用程序,在其中许多其他对象共享资源,那么谁仍然对资源具有强引用就变得更加模糊不清了。在这种情况下,通常有一个中心点,某种注册表,它持有对资源的唯一强引用,并只向客户端传递弱引用。这样可以保证如果资源管理器/注册表正在删除它,则资源可能会成为可回收的,否则某些其他对象可能仍然在某个列表、映射中保留着强引用。 - Roman Vottner
@pvg 谢谢,这回答了我的问题。然而,我仍然认为“dup”问题没有回答关于将值设置为null的具体问题。 - Shivam Sinha
1个回答

3
在您的例子中,这两种情况没有区别。但是,请考虑以下类似于您的示例的示例,其中存在区别:
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 
  }
}

AND

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

如果你有以下的编程代码:private String test = "testString"; private String another = "testString"; private WeakReference<String> cache = new WeakReference<String>(test); 然后尝试执行test = null;会发生什么? - AjCodez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接