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.
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.