Setting JVM heap size at runtime

Is there a way to set heap size from a running Java program?


No.

What you can do with an app that has very variable heap requirements is to set your max heap size very high with -Xmx and tune -XX:MaxHeapFreeRatio and -XX:MinHeapFreeRatio so that the app will not hang on to a lot of memory when the heap shrinks (it does that with default settings).

But note that this may cause performance problems when the memory actually used by the app varies both strongly and quickly - in that case you're better off having it hang on to all the memory rather than give it back to the OS only to claim it again a second later. You might also want to fiddle with the GC options to ensure that the GC doesn't leave too much unclaimed objects lying around, which it tends to do when there's a lot of room for the heap to grow, and which would defeat the goal of wanting the heap size to adjust to the app's needs.


According to http://www.dreamincode.net/forums/showtopic96263.htm, you can't do this at runtime, but you can spawn another process with a different heap size.


You can tweak those settings when you start your application but once the JVM is up and running those values cannot be changed. Something like this:

java -Xms32m -Xmx512m FooBar

will set the minimum heap size to 32MB and the maximum heap size to 512MB. Once these are set, you cannot change them within the running program.