Understanding The JAVA Memory Model

Basic Structure of the java memory model :

diagram 1

Below image will illustrate the above diagram much further,

diagram 2

Java memory model consists of Method Area, Heap and Stack area which is allocated for each thread.

Heap

Heap is used store object ( Class instances, Arrays , ...). JVM uses Garbage Collector to reclaim the memory occupied by the objects. If is object is not in use then the Garbage Collector reclaims the space that was allocated by that object. 
Garbage Collector is an daemon thread which acts like a background process.



Method Area

Stores the class structures.I'll be easy to understand if you at the "diagram 2". If a class is refered any more then it will be unloaded by the JVM using the Garbage Collector. This is similar to the scenario that happens in the heap.


Stack

A Stack will be allocated for each thread. One frame will be allocated for each method execution.

A frame store : 

  1. Local variables.
  2. Intermediate calculations of a method execution.
  3. Method parameters and return values.
Respective frames will be removed from the stack ones the tread execution completes.

PC Register

PC Register is created for each thread. It keeps a pointer to the statement that being executed at the moment in the tread. If the current method is a "Native method" ,then the PC register will be undefined.

Native Method Stack

Created for each thread. As the name explains it self, it is used for native methods. 

read more about native methods via this link

Frames

A frame is used to 
  1. Store data as we explained above and partial results. 
  2. To perform dynamic linking.
  3. Return values for methods.
  4. Dispatch Exception.

A new frame is created each time a method is executed.
Frame is destroyed when the method execution is complete.


SHARE

Harsha Jayamanna

    Blogger Comment
    Facebook Comment

1 comments: