I was reading about WeakReference and SoftReference.
Found the below:
WeakReference:
Counter counter = new Counter(); // strong reference - line 1
WeakReference<Counter> weakCounter = new WeakReference<Counter>(counter); //weak reference
counter = null; // now Counter object is eligible for garbage collection
Soft Reference:
Counter prime = new Counter(); // prime holds a strong reference - line 2
SoftReference<Counter> soft = new SoftReference<Counter>(prime) ; //soft reference variable has SoftReference to Counter Object created at line 2
prime = null; // now Counter object is eligible for garbage collection but only be collected when JVM absolutely needs memory
Here, anyways I am assigning null to the strong reference counter and prime and they are eligible for garbage collection and will be garbage collected when next GC cycle will run.
How is WeakReference / SoftReference impacting/assisting the garbage collection here?
UPDATE:
In the program below:
public class WeakReferenceSample {
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
WeakReference<HelloWorld> helloWorldReference = new WeakReference<>(helloWorld);
helloWorld = null;
System.out.println(helloWorld);
System.out.println(helloWorldReference.get());
System.gc();
System.out.println(helloWorldReference.get());
}
}
Even after changing helloWorld reference to null, my first System.out.println(helloWorldReference.get());is printing the object value and not null. After System.gc(), the second time it is printing as null. How this works internally as both the helloWorld reference and helloWorldReference reference point to the same HelloWorld object.
Sample output:
null
HelloWorld@2503dbd3
null
Proof: If I DO NOT assign null to helloWorld reference, then, both the helloWorld reference and helloWorldReference reference point to the same HelloWorld object.
HelloWorld@2503dbd3
HelloWorld@2503dbd3
HelloWorld@2503dbd3
Confused with how it works internally? Earlier I was thinking like it clones the object and then weak references it, but from the output, it does not look like.