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 are the Situations in Which You Choose HashSet or TreeSet in ...

How Can You Determine If Your Program Has a Deadlock in Java ?

What are the Java Collection Classes That Implement List Interfac ...

What are the Main Uses of Spring MVC Module ?

What is XMLBeanFactory in Spring Framework ?