Java: what about giving back the memory to the OS ?

Here is a common scenario when using Java for desktop applications:

  1. start a Java application
  2. run an algorithm which require a lot’s of memory
  3. release the memory once the algorithm is terminated
  4. start an other application (Java or not)
  5. swap the unused java memory of the first application

Between step 3 and 4 everyone would expect Java to give some MB back to the OS, but it does not. Thoses MB would be very useful to run the second application. By default Java will not give memory back to OS unless at least 70% of the Java memory is free. Moreover it will always allocate 40% more memory than needed. Theses ratio are controlled by two JVM options:

  • -XX:MaxHeapFreeRatio
  • -XX:MinHeapFreeRatio

I’ve been running Netbeans on large projects and large files (made by dirty developers, as Java files should never be large) with following options:

  • -XX:MaxHeapFreeRatio=10
  • -XX:MinHeapFreeRatio=10

and did not notice any performance issue. I no longer need to close Netbeans before running an other memory consuming application. I just close all tabs I do not need anymore, and can see the effect on system memory with the top command.

I thinks that 10% (or less ?) could be the default for long time running desktop applications. May be it’s also true for servers.

#java