-4

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?

Pratik
  • 908
  • 2
  • 11
  • 34
  • `isEnqueued()` will never return `true` when you don’t associate the soft reference with a queue. – Holger Feb 25 '19 at 12:20

1 Answers1

3

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
Amit Bera
  • 7,075
  • 1
  • 19
  • 42