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()

totalMemory()

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.

Runtime.getRuntime().totalMemory();

freeMemory()

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

Runtime.getRuntime().freeMemory();

maxMemory()

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.

Runtime.getRuntime().maxMemory();

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
Syntax
-Xmx<ammount of memory>
Example

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"); } }