2

How many objects will be eligible for garbage collection after completion of compute method?

I have searched this question and everywhere the answer is 1.

public void compute(Object p)

    {

     Object a = new Object();

     int x = 100;

     String str = "abc";

    }

But as far as I know, the string constant pool is a part of the heap now in Java 7 and eligible for garbage collection.

According to me, 2 objects are eligible for garbage collection i.e a and str.

Kenster
  • 23,465
  • 21
  • 80
  • 106
Bifrost
  • 417
  • 5
  • 23
  • 1
    Part of your confusion is your misconception about _variables_ and _objects_: `a` and `str` are simply variables, which might only reference some object (or maybe not). The objects being referenced on the other hand, they might be eligible for GC. – Seelenvirtuose Feb 09 '18 at 08:29
  • @kayamen, so basically you mean that str will also be garbage collected ? as suggested by link you shared – Bifrost Feb 09 '18 at 09:11

1 Answers1

3

It doesn't matter where objects get created.

The only thing that matters is: is the object alive?

In other words: when the last reference to an object goes out of use (or the holder of that reference isn't alive anymore) then the object is eligible for garbage collection.

An object created locally in a method can't be reached any more - it is no longer alive when the method returns. Things would be different for example if that method would add a to some (still live) "global" list for example.

Regarding str, there are multiple misconceptions:

  • no String object is created: the string literal goes into the constant pool. It would be a different story if you had used new String("abc") for example. In your case: no object, thus no garbage collection for that string.
  • str is holding a reference. There is no garbage collection for references, just for objects.
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • The little code snippet in this question shows 2 objects that could potentially be eligible for GC! The newly created one in the first line of the method. And the string `"abc"` in the third line. I think, we should explain, why the latter is not eligible for GC. – Seelenvirtuose Feb 09 '18 at 08:24
  • @Seelenvirtuose done ;-) – GhostCat Feb 09 '18 at 08:25
  • Just to be nitpicking: The string literal `"abc"` _is_ an object. It simply does not reside on the heap! The expression `new String("abc")` in fact deals with _two_ objects. – Seelenvirtuose Feb 09 '18 at 08:30
  • 1
    @Seelenvirtuose sure it resides on the heap, since Java 7. – Kayaman Feb 09 '18 at 08:56
  • 1
    @Seelenvirtuose, does this mean that GC does not happen in SCP area. ? if not then if i do str=null; what will happen to dangling object in SCP ? – Bifrost Feb 09 '18 at 09:01