How Stack and Heap Work in Java Multi-threading Environment ?

In Java, Stack and heap are memory areas available to an application. Every thread has its own stack. It is used to store local variables, method parameters and call stack.

Local variables stored in Stack of one Thread are not visible to another thread.

Where as, Heap is a common memory area in JVM. Heap is shared by all threads. All objects are created inside heap.

To improve performance thread can cache the values from heap into their stack. This can create problem if the same variable is modified by more than one thread.

In such a scenario we should used volatile keyword to mark a variable volatile. For a volatile variable the thread always reads the value from main memory.



You May Interest

How Can You Upload a Large File in JSP ?

What is the Difference Between wait and sleep Methods in Java ?

What is the Difference Between Sleep and Wait Methods in Java ?

What is Difference Between Include Directive and Include Action o ...

What is the Main Benefit of IOC Principle in Java ?