8

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?

Mat
  • 202,337
  • 40
  • 393
  • 406
Nav
  • 10,304
  • 20
  • 56
  • 83
  • You can't put stuff on the stack which could be cleared by the garbage collector. – svens Dec 04 '11 at 17:53
  • @svens actually not true - the JIT will allocate objects on the stack if it can, but obviously GC on a stack doesn't make any sense - how would that work? – Voo Dec 04 '11 at 18:04

4 Answers4

10

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

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
8

There is no garbage that lives on the stack.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
4

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.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

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

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130