Java heap size (memory) allocation

The amount of memory that a Java program is allowed to use depends on its environment. Java Standard library provides the following methods in the runtime class.

  1. totalMemory()
  2. freeMemory()
  3. maxMemory()


The totalMemory() returns the total amount of memory in the JVM. The value returned by this method may vary over time, depending on the host environment.



The freeMemory() returns the amount of free memory in the JVM. Calling the gc method may result in increasing the value returned by freeMemory.



The maxMemory() returns the maximum amount of memory that the JVM will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned.


What are the Xms and Xmx parameters?

The flag -Xmx < memory > specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while -Xms< memory > specifies the initial memory allocation pool. The memory flag can also be specified in multiple sizes, such as kilobytes, megabytes, and so on.

-Xmx1024k -Xmx512m -Xmx8g
-Xmx<ammount of memory>

Starting a JVM like below will start it with 256MB of memory, and will allow the process to use up to 2048MB of memory:

java -Xmx2048m -Xms256m

The following program will output jvm options and the used, free, total and maximum memory available in jvm.

public class GetMemoryDeatils { public static void main(String args[]) { System.out.println("Used Memory : " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + " bytes"); System.out.println("Free Memory : " + Runtime.getRuntime().freeMemory() + " bytes"); System.out.println("Total Memory : " + Runtime.getRuntime().totalMemory() + " bytes"); System.out.println("Max Memory : " + Runtime.getRuntime().maxMemory() + " bytes"); } }