Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the stack garbage collected in Java?

The heap memory is garbage collected in Java.

Is the stack garbage collected as well?

How is stack memory reclaimed?

like image 713
giri Avatar asked Mar 15 '10 13:03

giri


People also ask

Does garbage collector work on stack memory?

Sizes of stack and heap memory can be changed by specifying options to JVM. After an object is no longer used by the program, Java garbage collector reclaims the memory for reuse by other programs.

What is garbage collection in stack?

Garbage Collection was invented in order to cope with the problem of allocating things on a heap, i.e. such that you cannot predict which parts will be released first. GC is meant for memory allocation problems where stack management is not sufficient. Copy link CC BY-SA 2.5.

Is Java garbage collected?

Java Memory Management, with its built-in garbage collection, is one of the language's finest achievements. It allows developers to create new objects without worrying explicitly about memory allocation and deallocation, because the garbage collector automatically reclaims memory for reuse.

Which objects are garbage collected in Java?

Java Garbage collector tracks the live object and objects which are no more need are marked for garbage collection. It relieves developers to think of memory allocation/deallocation issues. When an object created in Java program is no longer reachable or used it is eligible for garbage collection.


2 Answers

The memory on the stack contains method-parameters and local variables (to be precise: the references for objects and variables itself for primitive types). That will be automatically removed if you leave the method. If the variables are references (to objects) the objects itself are on the heap and handled by the garbage collector.

So the stack isn't garbage collected in the same way as the heap, but stack is a form of automatic memory-management in it's own (which predates garbage collection).

A more detailed answer is given by Thomas Pornin, look into that for more details.

like image 84
Mnementh Avatar answered Sep 18 '22 04:09

Mnementh


The stack is not garbage collected in Java.

The stack allocated for a given method call is freed when the method returns. Since that's a very simple LIFO structure, there's no need for garbage collection.

One place where the stack and garbage collection interact is that references on the stack are GC roots (which means that they are the root references from which reachability is decided).

like image 23
Joachim Sauer Avatar answered Sep 21 '22 04:09

Joachim Sauer