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

What is Thread Starvation in Java ?

What are the Main Uses of Singleton Design Pattern in Java ?

What is a CAS Operation in Java ?

Why Do We Use JSP Instead of Servlet in Java ?

What is the Difference Between an Iterator and ListIterator in Ja ...