Java Set Heap Size Example

So what the heck is a Java Heap? Very glad you asked. The Java Heap is where the objects that make up your Java program live. The Java Heap is the container for all of the live objects, dead objects, and free memory.

The Java Virtual Machine (JVM) heap size determines the frequency and the duration of how much time the Virtual Machine (VM) spends collecting garbage. What is garbage? In Java garbage is any object that is not longer referenced.

For example, if you set the Java heap size to a low value, garbage collection is fast but it happens more often. Likewise, if you set the Java heap size to a high value, garbage collection will be slower but occur less frequently.


Java Heap Size Parameters

It is optimal to tune the following parameters to the needs of your specific application. You have three options to set these two parameters. You can use (k) for kilobytes, (m) for megabytes, or (g) for gigabytes. This example will be using (m) for megabytes.

  • -Xms (Set initial Java Heap size)
  • -Xmx (Set maximum Java Heap size)

If your compiling and running your Java program in Eclipse, you can set the Java Heap in the Run Configurations VM arguments section. In this example, we are setting the initial Java heap size to 256 megabytes and the max Java heap to 512 megabytes.


Set Java Heap Size Command Line

If your running your Java program from the windows command line or from a shell script on Linux, then you would include the -Xms and -Xmx on the command line similar to this example.



Concluding Comments

It’s best to fine tune the initial and max Java heap size to your specific Java program. You really don’t want the Java garbage collector (gc) running for tool long or too often. It’s a balance that will take some trial and error to get it right.

Add a Comment

Your email address will not be published. Required fields are marked *