Explain Java Memory model

The JVM divided the memory into following sections.

    Heap,Stack,Code,Static

  1.     The code section contains your byte-code.
  2.     The Stack section of memory contains methods, local variables and reference variables.
  3.     The Heap section contains Objects (may also contain reference variables).
  4.     The Static section contains Static data/methods.
Now the question is How does Java allocate stack and heap memory ? 

Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.

In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is thread safe (each thread will have its own stack) but the heap is not thread safe unless guarded with synchronization through your code.

Check for Heap and Stack memory for multi threaded application here.

core java 12

FOLLOW US ON LinkedIn



Explore Tutu'rself