1

How are anonymous objects, like used in case of return statements for example :
return new JsonObject().put("name","xyz") are allocated in the Heap ? As they don't have any named references, how does the Garbage Collector clear them from the memory ? I tried looking for the answers but couldn't find one, so posting it here.

DebashisDeb
  • 392
  • 5
  • 13

2 Answers2

2

If an instance is not available (reachable) within the code, then it's dead. When the gc runs, it identifies the live set, not the set of dead objects. The JVM has its own way of keeping track of live objects.
The collector will trace the live set, marking all live objects.
Then the collector will, depending on the type, either move the live set to another memory area (copying collector) or traverse the heap, deleting dead objects as it finds them and optionally compacting the heap.
In your specific case, the fact that an anonymous object has no specific reference doesn't really matter to the gc since it has its way of keeping track of live and dead objects.

Erik
  • 2,013
  • 11
  • 17
  • You may point to the contradiction of the question: if there was a named reference to the object, it wasn’t eligible to garbage collection. In other words, since objects are *always* collected when there is *no* reference to it, it doesn’t matter whether there was a named reference in the object’s past. – Holger Feb 23 '18 at 15:22
  • @Holger Yes, I could have but there seemed to be a confusion of ideas that I did not want to add to. – Erik Feb 24 '18 at 21:19
1

There are similar questions here; Inner Class has an implicit reference to the outer class and may can leak memory and a pretty good description here http://viralpatel.net/blogs/inner-classes-in-java/

Note the line;

An object of an inner class has an implicit reference to the outer class object that instantiated it.

You can see this in a simple test;

    public class Frame1
    {
            public class JsonObject
            {
                    int field1 = 123;
                    int field2 = 456;

                    public JsonObject() { }
            }

            // code that callSomething()
            // ...

            private Object callSomething()
            {
                    return new JsonObject();
            }
    }

I added a breakpoint on the return line and allowed the code to step far enough so the JsonObject was created. Then after attaching JVisualVM and looking at the only JsonObject instance on the heap I saw;

enter image description here

There is a reference to the outer Frame1 class

Paul MacGuiheen
  • 628
  • 5
  • 17