Search code examples
javaweak-references

Weak Reference vs setting to Null


What is the difference between using WeakReference and setting the strong ref type to null ?

Say for example in the following code the variable "test" is a strong ref to "testString". When I set the "test" to null. There is no longer a Strong ref and hence "testString" is now eligible for GC. So if I can simply set the object reference "test" to equal null what is the point of having a 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 
  }
}

Why would i ever want to use 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 
  }
}

Solution

  • In your example, there is no difference between the two cases. However, consider the following example similar to yours where there is a distinction:

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