1 Stack And Heap Flashcards
Points to remember
Where are local variables and Objects kept?
- Local variables are always kept on the stack. Objects are always stored in the heap
Stack Semantics (threads)
JVM may have several threads. Each thread is given a fixed amount of stack space that is dedicated completely and exclusively to that thread. No one but that thread can access its stack space. This is called ”stack semantics”. A thread accesses its stack space by creating and using variables. There is no other special way of accessing the stack space.
”heap semantics”
Heap space is shared among all threads. Any thread can use space on a heap by creating objects. Since heap space is shared, it is possible for one thread to access objects created by another if it has a reference to that object. This is called ”heap semantics”.
Stack snd Heap space
Stack space is limited for a program. So if you have a huge chain of method calls where each method creates a lot of temporary variables (recursion is a good example), it is possible to run out of stack space. In Java, the default stack space size is 64KB but it can be changed at the time of executing the program using command line option -Xss . Heap space is unlimited from the program’s perspective. It is limited only by the amount of space available on your machine.
Which variables are stored in the stack space?
Only temporary variables i.e. variable created in a method (also known as local variables and automatic variables) are created on the stack space. Everything else is created on the heap space. If you have any doubt, ask yourself this question -is this a temporary variable created in a method? Yes? Then it is created on the stack. No? Then it is on the heap. Actual objects are ALWAYS created on the heap
When a method is invoked by a thread, it uses………..to keep its temporary variables.
When a method is invoked by a thread, it uses the thread’s stack space to keep its temporary variables.
Which variables are removed and from where when a method ends?
Variables added to the stack space by a method are removed from the stack when that method ends. Everything else created by a method is left on the heap even after the method ends.