Monday, 24 April 2017

JVM Memory Model



JVM Memory Model

Java Memory Model, JVM Memory Model, Memory Management in Java, Java Memory Management
As you can see in the above image, JVM memory is divided into separate parts. At broad level, JVM Heap memory is physically divided into two parts – Young Generation and Old Generation.
  • Most of the newly created objects are located in the Eden memory space.
  • When Eden space is filled with objects, Minor GC is performed and all the survivor objects are moved to one of the survivor spaces.
  • Minor GC also checks the survivor objects and move them to the other survivor space. So at a time, one of the survivor space is always empty.
  • Objects that are survived after many cycles of GC, are moved to the Old generation memory space. Usually it’s done by setting a threshold for the age of the young generation objects before they become eligible to promote to Old generation.

Permanent Generation

Permanent Generation or “Perm Gen” contains the application metadata required by the JVM to describe the classes and methods used in the application. Note that Perm Gen is not part of Java Heap memory.
Perm Gen is populated by JVM at runtime based on the classes used by the application. Perm Gen also contains Java SE library classes and methods. Perm Gen objects are garbage collected in a full garbage collection.

Method Area

Method Area is part of space in the Perm Gen and used to store class structure (runtime constants and static variables) and code for methods and constructors.

Memory Pool

Memory Pools are created by JVM memory managers to create a pool of immutable objects, if implementation supports it. String Pool is a good example of this kind of memory pool. Memory Pool can belong to Heap or Perm Gen, depending on the JVM memory manager implementation.

Runtime Constant Pool

Runtime constant pool is per-class runtime representation of constant pool in a class. It contains class runtime constants and static methods. Runtime constant pool is the part of method area.

Java Stack Memory

Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method.



Java Heap Space

Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create any object, it’s always created in the Heap space. Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application.

Java Stack Memory

Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method. Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method.
Stack memory size is very less compared to Heap memory.
Let’s understand the Heap and Stack memory usage with a simple program.

Java Method Area

  • When the Java virtual machine loads a type, it uses a class loader to locate the appropriate class file.
  • The class loader reads in the class file--a linear stream of binary data--and passes it to the virtual machine.
  • The virtual machine extracts information about the type from the binary data and stores the information in the method area.
  • Memory for class (static) variables declared in the class is also taken from the method area.


Stack Memory :

1. Program Counter (PC) Register

In general computer architecture terms, program counter (PC) register keeps track of the current instruction executing at any moment. That is like a pointer to the current instruction in sequence of instructions in a program. This is same in Java JVM terms also. We have multithreaded architecture as Java supports multithreading and so, a program counter (PC) Register is created every time a new thread is created. PC keeps a pointer to the current statement that is being executed in its thread. If the current executing method is ‘native’, then the value of program counter register will be undefined.

2. Java Virtual Machine Stacks

JVM stacks are used to store Java virtual machine frames. JVM will not do any manipulation directly with the stacks and they are only storage units for frames. Memory size of stacks can be of two types, fixed and varying size. Varying size can dynamically expand as per the need. Java JVM frames are created when a method is invoked, it performs the dynamic linking. JVM stacks are created and managed for each thread.
  • StackOverflowError – this error occurs in fixed size JVM stacks, if the memory size is not sufficient during the program execution.
  • OutOfMemoryError – in dynamic sized stacks, while trying to expand for more memory need and there is no additional memory available to allocate and we get OutOfMemoryError.

3. The Stack Frame

  • The stack frame has three parts:
    1. local variables
    2. operand stack
    3. frame data.




Below image shows the Stack and Heap memory with reference to above program and how they are being used to store primitive, Objects and reference variables.




  • As soon as we run the program, it loads all the Runtime classes into the Heap space. When main() method is found at line 1, Java Runtime creates stack memory to be used by main() method thread.
  • We are creating primitive local variable at line 2, so it’s created and stored in the stack memory of main() method.
  • Since we are creating an Object in line 3, it’s created in Heap memory and stack memory contains the reference for it. Similar process occurs when we create Memory object in line 4.
  • Now when we call foo() method in line 5, a block in the top of the stack is created to be used by foo() method. Since Java is pass by value, a new reference to Object is created in the foo() stack block in line 6.
  • A string is created in line 7, it goes in the String Pool in the heap space and a reference is created in the foo() stack space for it.
  • foo() method is terminated in line 8, at this time memory block allocated for foo() in stack becomes free.
  • In line 9, main() method terminates and the stack memory created for main() method is destroyed. Also the program ends at this line, hence Java Runtime frees all the memory and end the execution of the program.


For another example


  1. JVM loads MyClass.class file by using ClassLoader.
  2. ClassLoader reads the .class file in the form of bytes and passes to JVM.
  3. JVM will extract the data from above binary stream and it stores the total code into Method Area.(Now total code is available in Method Area ).
  4. JVM creates a thread with name ‘main’
  5. Along with ‘main’ thread one stack area will be created.(without any frames)
  6. ‘Main’ thread executes line-1 and creates memory for ‘x’ in ‘Method Area’
  7. ‘Main’ thread executes line-2 (Internally PC holds address of current executing instruction)
  8. One frame is created on stack for static block.
  9. Executes line-3 and print the currently executing thread name.
  10. Creates a memory for a variable ‘a’ and assigns value 10 on line-4.
  11. Creates a object in String constant pool area of heap space and the reference is hold by variable ‘s’ on line-5.
  12. Execute line-6 and print the data.
  13. Executes line-7 , static block is completed so remove the frame from stack.
  14. Executes line-8, creates an object in Heap space and the reference is hold by variable ‘o’ and stored in ‘Method Area’.
  15. Executes line-9, creates memory for variable ‘i’ in Heap space.
  16. Main thread calls main(), so line -10 will execute.
  17. Main thread creates a frame in stack for main().
  18. Similar to above example only memory will creates in stacks.



public class MyClass {

int a =10;// 17
Integer b = 11;// 18
String c = "rama"; // 19
boolean flag; // 20
static int x = 35; //1
static{ // 2
System.out.println("I am in static block = "+Thread.currentThread().getName()+" thread");// 3
int a = 10;// 4
String s = "sitha";// 5
System.out.println(a+" "+s); // 6
}// 7
static Object o = new Object();// 8
static int i = 12; // 9
{// 21
System.out.println("print instance variable 'a' in instance block before constructor = "+a);//22
a = 30;// 23
}// 24
public MyClass() {// 15
super();//16
System.out.println("print instance variable 'a' in constructor = "+a);// 25
System.out.println("I am in MyClass() constructor = "+Thread.currentThread().getName()+" thread");// 26
flag = true;// 27
System.out.println("flag value = "+flag);// 28
}// 29
public static void main(String[] args) {//10
System.out.println("I am in main method = "+Thread.currentThread().getName()+" thread");// 11
int a = 20; //12
o = new Object();// 13
MyClass my = new MyClass();// 14
my.m1(a, o);// 30
}// 37
public void m1(int p, Object q){//31
System.out.println("I am in m1() method = "+Thread.currentThread().getName()+" thread");// 32
p = 100; // 33
String s = q.toString(); //34
System.out.println(s); //35
}// 36

}






1 comment:

3. Java Program to create Binary Tree