Java Language Java Memory Management Setting the Heap, PermGen and Stack sizes


When a Java virtual machine starts, it needs to know how big to make the Heap, and the default size for thread stacks. These can be specified using command-line options on the java command. For versions of Java prior to Java 8, you can also specify the size of the PermGen region of the Heap.

Note that PermGen was removed in Java 8, and if you attempt to set the PermGen size the option will be ignored (with a warning message).

If you don't specify Heap and Stack sizes explicitly, the JVM will use defaults that are calculated in a version and platform specific way. This may result in your application using too little or too much memory. This is typically OK for thread stacks, but it can be problematic for a program that uses a lot of memory.

Setting the Heap, PermGen and default Stack sizes:

The following JVM options set the heap size:

  • -Xms<size> - sets the initial heap size
  • -Xmx<size> - sets the maximum heap size
  • -XX:PermSize<size> - sets the initial PermGen size
  • -XX:MaxPermSize<size> - sets the maximum PermGen size
  • -Xss<size> - sets the default thread stack size

The <size> parameter can be a number of bytes, or can have a suffix of k, m or g. The latter specify the size in kilobytes, megabytes and gigabytes respectively.


$ java -Xms512m -Xmx1024m JavaApp
$ java -XX:PermSize=64m -XX:MaxPermSize=128m JavaApp
$ java -Xss512k JavaApp

Finding the default sizes:

The -XX:+printFlagsFinal option can be used to print the values of all flags before starting the JVM. This can be used to print the defaults for the heap and stack size settings as follows:

  • For Linux, Unix, Solaris and Mac OSX

    $ java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

  • For Windows:

    java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"

The output of the above commands will resemble the following:

uintx InitialHeapSize                          := 20655360        {product}
uintx MaxHeapSize                              := 331350016       {product}
uintx PermSize                                  = 21757952        {pd product}
uintx MaxPermSize                               = 85983232        {pd product}
 intx ThreadStackSize                           = 1024            {pd product}

The sizes are given in bytes.