garbage-collectionsoft-references

When is the SoftReference itself reclaimed by GC?


When the object referenced by the SoftReference is reclaimed by the garbage collector, how does the garbage collector deal with the SoftReference itself?


Solution

  • In JVM whenever there are no more references to the SoftReference object itself. References to SoftReference objects works "normal". Assuming the reference is strong.

    String myString = "...";
    SoftReference<String> softReference = new SoftReference<String>(myString);
    // ... do some stuff
    
    softReference = null; // no references to the SoftReference object itself so in the next garbage collector cycle, it will be garbaged collected.