Memory Usage in Java

Published: Saturday, 10 December 2011

Java memory tuning and performance notes.

You can allocate memory to the JVM when it starts up. This is to limit the amount of resources the JVM process can use your machine.

If you do not specify memory settings then the JVM will automatically allocate limits when it is created.

To see how much memory is being used, take a look at the available monitoring tools.

Heap Space

java.lang.OutOfMemoryError: Java heap space

If you see an OutOfMemoryError exception telling you about heap space, you could increase it using the -Xmx JVM parameter. e.g.

java -Xmx512m

To allocate a maximum of 512M of memory to the JVM.

Type java -X for a list of JVM specific standard parameters

PermSize

If you see an exception such as:

java.lang.OutOfMemoryError: PermGen space

Use -XX:MaxPermSize to increase the bucket for permanent generation memory. e.g. to set the maximum to 512m use

java -XX:MaxPermSize=512m

If your application uses numerous classes you may need to increase this setting.

Monitoring

You can use JMX to inspect the JVM while it is running. There are tools that come with the JDK in the bin directory.

jconsole

jconsole is a GUI that can attach to running JVMs. From here you can inspect memory.

jmap

Determine the PID of the JVM, then you can get information about memory. This is useful if the JVM is so unresponsive that jconsole cannot connect. To avoid permission errors, you should run jmap with the same user that is running them JVM process.

$ jmap.exe -heap 5568
Attaching to process ID 5568, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 24.45-b08

using thread-local object allocation.
Parallel GC with 4 thread(s)

Heap Configuration:
   MinHeapFreeRatio = 40
   MaxHeapFreeRatio = 70
   MaxHeapSize      = 2134900736 (2036.0MB)
   NewSize          = 1310720 (1.25MB)
   MaxNewSize       = 17592186044415 MB
   OldSize          = 5439488 (5.1875MB)
   NewRatio         = 2
   SurvivorRatio    = 8
   PermSize         = 21757952 (20.75MB)
   MaxPermSize      = 85983232 (82.0MB)
   G1HeapRegionSize = 0 (0.0MB)

Heap Usage:
PS Young Generation
Eden Space:
   capacity = 710934528 (678.0MB)
   used     = 0 (0.0MB)
   free     = 710934528 (678.0MB)
   0.0% used
From Space:
   capacity = 524288 (0.5MB)
   used     = 0 (0.0MB)
   free     = 524288 (0.5MB)
   0.0% used
To Space:
   capacity = 524288 (0.5MB)
   used     = 0 (0.0MB)
   free     = 524288 (0.5MB)
   0.0% used
PS Old Generation
   capacity = 1422917632 (1357.0MB)
   used     = 107998376 (102.99527740478516MB)
   free     = 1314919256 (1254.0047225952148MB)
   7.589924642946585% used
PS Perm Generation
   capacity = 85983232 (82.0MB)
   used     = 85983216 (81.99998474121094MB)
   free     = 16 (1.52587890625E-5MB)
   99.99998139172065% used

26816 interned Strings occupying 2723864 bytes.

In the above example it shows that the PS Perm Generation is full.