Case -1 :
new Demo().abc();
Here, we are not maintaining any explicit reference to the newly created Demo
instance. But inside the abc()
, the this
reference will point to the newly created instance. So, if the reference doesn't leak from abc()
, as soon as the method returns, the newly created Demo
instance will be ready for GC (As it becomes unreachable from any thread).
If there is a reference leak like this :
public void abc()
{
someOtherMethod(this); // starts another thread and does something else
...
}
In the above case, even when abc()
returns, the Demo
instance created could still be reachable and thus will not be eligible for GC.
Case -2 :
Demo demo=new Demo();
demo.abc();
demo=null;
Here as soon as you set demo
to null
and assuming abc()
doesn't leak the reference of demo
to some other thread, your demo
instance will become unreachable as soon as you set it to null
and thus, it will be eligible for GC.