Nav
Nav

Reputation: 10422

Does the Java garbage collector clean stack memory?

Is the garbage collector in Java used for clearing unused objects from heap memory only, or does it actually lend a hand in cleaning the stack memory too?

Upvotes: 8

Views: 4455

Answers (4)

Aniket Thakur
Aniket Thakur

Reputation: 68935

Garbage collection only happens on heap for Objects that are no longer reference from any GC roots.

Stack is where your local variables (like primitives and object references) live. There is no concept of GC here. Think of stack data structure. If a local variable is in scope (of a particular thread's stack frame) it is pushed to this stack frame and when it is out of the scope it is poped out of stack frame.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533530

Its objects which don't have a strong reference from a thread stack which can be cleaned up.

Upvotes: 0

Etienne de Martel
Etienne de Martel

Reputation: 36851

The only things that lives on the stack are references and instances of primitive types. Both of those are ignored by the garbage collector.

Upvotes: 11

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

There is no garbage that lives on the stack.

Upvotes: 8

Related Questions