In the Java runtime, if my application frees memory, does the runtime release the memory back to the OS? Or just back to my process?
2 Answers
That depends on the JVM implementation and isn't specified in the specification.
The Sun JVM will hold onto it as a first step. Once a certain (configurable) percentage of allocated memory is unused, it will return some of it to the OS (the behavior is influenced by the MinHeapFreeRatio
and MaxHeapFreeRatio
settings).

- 302,674
- 57
- 556
- 614
-
I've never seen the Java VM act terribly aggressive about returning memory to the system--probably a good thing as a default. Java processes tend to be long running and constantly expanding and contracting can fragment memory. For most server-side solutions, releasing memory would lead to non-deterministic behavior and poor performance, however it would be nice if they left that decision to the users (with the -Xmx/-Xms settings). – Bill K Nov 14 '16 at 20:08
Back to the process first, but also could go back to the OS in the end. Memory allocated by the GC is in a big contiguous chunk (the heap) or set of chunks, and GC "freeing" simply frees up the allocation in the heap, but not necessarily back to the OS. Once the GC compacts, it may be possible for the VM to return some memory to the OS.
The GC wants to hold on to a certain amount of space so it can quickly service future "new" requests for memory. So GC makes requests to the OS for memory in large segments, as seldom as possible.

- 20,467
- 1
- 59
- 80