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.
- Java Interview Questions-Core Faq
- Important features of Java
- What is the difference between JDK and JRE?
- What gives Java its 'write once and run anywhere' nature?
- What is JVM and is it platform independent?
- What is Just-In-Time (JIT) compiler?
- What is the garbage collector in Java?
- What is NullPointerException in Java
- Difference between Stack and Heap memory in Java
- What is numeric promotion?
- Why do we need Generic Types in Java?
- What does it mean to be static in Java?
- What are final variables in Java?