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.
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.
Starting a JVM like below will start it with 256MB of memory, and will allow the process to use up to 2048MB of memory:
The following program will output jvm options and the used, free, total and maximum memory available in jvm.