Oct 11, 2017

Understanding JVM: Memory Areas in JVM - Part 1

Whenever JVM load and run a Java program, it needs memory to store several things like bytecode, objects, variables, etc. Total JVM memory is organized into following:

  • Method Area
  • Heap Area
  • Stack Area
  • PC Registers
  • Native Method Stack

1. Method Area

  • It is created at the time of JVM startup.
  • .class file's binary information is stored into method area.
  • Static variables are stored in method area.
  • Data inside method area is not thread safe.
  • Method area is not contiguous memory.
  • For every JVM, one method area is available.
  • Constant pools of a class are store inside method.

2. Heap Area

  • There is one heap area per JVM.
  • Like method area, it is also created at the time of JVM startup.
  • Need not be contiguous memory.
  • Objects and corresponding instance variables are stored in the heap area.
  • Every array in Java is object only, hence arrays will also be stored in heap area.
  • Heap area can be accessed by multiple threads, and hence data in heap area is not thread safe.
Program to Display heap memory statistics
Heap memory statistics can be captured using Runtime instance. Runtime class is present in java.lang package. It is a singleton class.
Following code snippet demonstrate how Runtime object can be obtained and used to get heap statistics:

package com.javaterritory;

public class MemoryTest {

 public static void main(String[] args) {
  Runtime r = Runtime.getRuntime(); // get instance of Runtime
  System.out.println("Max memory: " + r.maxMemory()); // prints memory (number of bytes) allocaed to JVM
  System.out.println("Total memory: " + r.totalMemory()); // prints initial memory (in bytes) allocated to JVM
  System.out.println("Free memory: " + r.freeMemory()); // prints the free memory 
 }
}

Following were the results when I executed it on my machine:

Max memory: 3797417984
Total memory: 257425408
Free memory: 254741016

How to set maximum and minimum heap size
Following JVM arguments can be used to configuring heap size;
-Xmx 512m : to set maximum heap size to 512 mb
-Xms 64m : to set initial heap size to 64 mb

This is it for Method and Heap area. Next section will cover the stack memory area.
If you like reading our article, connect with us at +Java Territory  / Java territory to stay updated.

0 comments:

Post a Comment