Search code examples
javagarbage-collectionsoft-references

SoftReference is not getting cleared by Java GC


I was trying to understand SoftReferences in Java which basically ensures clearing memories of SoftReferenced objects before throwing StackOverflowError.

public class Temp 
{

    public static void main(String args[])
    {
        Temp temp2 = new Temp();
        SoftReference<Temp> sr=new SoftReference<Temp>(temp2);

        temp2=null;
        Temp temp=new Temp();
        temp.infinite(sr);

    }

    public void infinite(SoftReference sr)
    {

        try
        {
            infinite(sr);
        }
        catch(StackOverflowError ex)
        {
            System.out.println(sr.get());
            System.out.println(sr.isEnqueued());
        }

    }
}

However the outcome of above was

test.Temp@7852e922
false

Can someone explain me why the object was not cleared by GC? How can I make it work?


Solution

  • Looks like you may have some confusion with the StackOverFlowError and OutOfMemoryError. StackOverFlowError and OutOfMemoryError error are different. StackOverFlowError happens when there is no space in the call stack: OutOfMemoryError occurs when the JVM is unable to allocate memory in the heap space for a new object. Your code leads to StackOverflow: that means stack memory is full, not the heap space. I believe there will be enough space to store your SoftReference that's why it does not GCd the object.