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 Be Read Data From a Form in a JSP ?

What are the Thread-safe Classes in Java Collections Framework ?

What is a WeakHashMap in Java ?

Why Collection Interface Doesn’t Extend Cloneable and Serializabl ...

What are the Examples of Observer Design Pattern in JDK ?