Sunday 29 July 2012

Java - Runtime Memory Areas

Stack and heap are two very important memory areas.
However before starting stack and heap or primitives vs objects lets have a closer look how JVM divides runtime memory area:

Each JVM has a class loader - a mechanism for loading classes, interfaces.etc.. 
Each JVM also has an execution engine - a mechanism responsible for executing the instructions contained in the methods of loaded classes.

So when a JVM runs a program, it needs memory to store many things (bytecodes, objects the program instantiates, parameters to methods, return values, local variables, intermediate results....etc ).
The JVM organizes the memory it needs to execute a program into several runtime data areas.



















Each instance of JVM has one method area and one heap. These areas are shared by all threads running inside virtual machine. 
Anything that it loads, JVM must store the below information in method area:
  • The fully qualified name (For example, the fully qualified name of class Object in package java.lang is java.lang.Object. )
  • The fully qualified name of the type’s direct superclass 
  • Whether it is a class or an interface

Heap: Whenever a class instance or array is created in a running Java application, the memory for the new object is allocated from a single heap. As there is only one heap inside a JVM instance, all threads share it. 

Stack: However each thread running inside a JVM instance, gets its own pc register and Java stack. If the thread is executing a Java method, the value of pc register indicates the next instruction to execute. A thread’s Java stack stores the state of Java method invocations for the thread. It includes its local variables, the parameters with which it was invoked, its return value, and intermediate calculations.


Now consider the below 2 statements:
int num = 5; //primitive data type
Student s = new Student(); // Student is a class having name as an attribute.

Primitive datatypes are located on the stack and we can only access their value,
while objects are located on heap and we have a reference to these objects.

Native methods stack: The state of native method invocations is stored in an implementation-dependent way in native method stacks.



No comments:

Post a Comment