Home > Mobile >  Garbage collection of objects created locally in a method
Garbage collection of objects created locally in a method

Time:03-14

I think if an object gets created locally within a method and is never leaked outside then that object will be eligible for garbage collection as soon as that method executed is completed.

But I am confused because I read that there are 4 GC roots - and one of then is the thread object, so I am confused that is it the case that method local objects will become eligible for garbage collection only when the thread in which it got created is complete and the GC Root of that thread is taken off?

Also, if someone can throw some light on how method local objects are linked to stack area of the heap.

PLEASE NOTE that I have read about GC of method local objects but nowhere I got a clear and detailed answer so I raised this question.

CodePudding user response:

Think of the thread call stack as a doubly linked list of stack frame nodes. Each node references all the local variables for a given method, and these in turn reference any live objects. The GC root for the thread is essentially the head node of the linked list, and garbage collection traces the nodes that are still linked, thus finding all live objects. When a method returns, the tail node of the linked list is removed, and thus it's not discoverable by GC anymore.

In practice, the call stack isn't implemented this way, but the behavior is essentially the same.

CodePudding user response:

Method local objects are eligible for garbage collection as soon as they stop being used, whether or not the method is finished.

Methods really have almost nothing to do with garbage collection.

  • Related