2

If I have a class Sample and I have an instance method, instanceMethod in it. The class has a main method where I create an object of Sample itself and call it's instanceMethod without using a reference variable.

like this:

new Sample().instanceMethod();

inside the main.

Since this object has NO reference, will the garbage collector collect it ?

Amogh Talpallikar
  • 12,084
  • 13
  • 79
  • 135

1 Answers1

7

In Java1, I don't believe the object can be collected while instanceMethod() is being executed. In the main method's stack frame there is a reference to the object, at least logically (the JIT compiler may elide it). The fact that you're not assigning it to a variable doesn't affect the bytecode very much.

Of course when instanceMethod() completes, the object may be eligible for garbage collection - but it may not. For example, instanceMethod() may store a reference to this in a static variable.

Basically it's not worth getting hung up over intricate corner cases - just rely on the GC collecting objects which can't be reached any more in any way, but not collecting objects which may still be in use.


1 In .NET an object can still be garbage collected while an instance method is executing "in" the object, if the JIT compiler can prove that none of its variables will be read again. It's very confusing, and can cause very subtle bugs.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • But say if instance method spawns multiple threads and they are reffered within Sample object. once instanceMethod is over. won't references to thos threads will be lost if this obj is garbage collected ? – Amogh Talpallikar Jan 02 '12 at 10:38
  • 1
    @AmoghTalpallikar: The threads would still be running, and if those threads actually refer to the object, then that would keep the object alive too. But yes, if it *just* starts threads and remembers reference to those threads, then the object could be collected and those variables lost... but then you couldn't access those variables anyway, so it makes no difference. – Jon Skeet Jan 02 '12 at 10:41
  • Newer findings are, in Java [objects may get collected while instance methods are running](http://stackoverflow.com/a/26645534/2711488) as well. So Java and .NET are on par in this regard. – Holger May 08 '15 at 10:00