Does GC release back memory to OS?
Short Answer: The memory is returned back to the operating system immediately or at a later time depends upon the configuration (algorithm) of the garbage collector.
JDK 1.8
If you are using JDK 8 or earlier and run below code snippet:
public static void main(String[] args) throws InterruptedException {
Runtime runtime = Runtime.getRuntime();
long availableMemory = runtime.freeMemory();
System.out.println("Initially Available Memory : " + availableMemory);
List<Customer> customers = new ArrayList<>();
for (int loop = 0; loop < 1_00_000; loop++) {
customers.add(new Customer("USERNAME"));
}
availableMemory = runtime.freeMemory();
System.out.println("Post Processing Available Memory : " + availableMemory);
customers= new ArrayList<>();
Thread.sleep(1000);
System.gc();
availableMemory = runtime.freeMemory();
System.out.println("Post Garbage Collecting Available Memory : " + availableMemory);
}
Using JDK 1.8 it results in the below statistics on my machine:
Initially Available Memory : 243620776
Post Processing Memory : 240444976
Post Garbage Collecting Memory : 250960720
Results: In the case of JDK 1.8, when we call the System.gc()
we get the free memory back and JVM receives it and doesn't return it to the OS.
JDK 11+
When running the same above code snippet, we yield a surprising result:
Initially Available Memory: 242021048
Post Processing Memory: 239171744
Post Garbage Collecting Memory: 61171920
Results: In the case of JDK 11+, when we call the System.gc()
JVM frees the memory and returns it to the OS.
Consequences:
Whenever we return the free memory to the Operating System, if we require more memory we have to request to the OS for a free chunk of additional memory. The overhead results in slow performance.
Request JDK 11+ not to release free memory back to the OS.
We can set the initial heap size to high, that way we can simply ensure that we never face such a situation. We can set the initial heap size high by -Xms
.
$ java -Xms2g MyProgram.java
Initially Available Memory : 2124414976
Post Processing Memory : 2120842392
Post Garbage Collecting Memory : 2144444600
I have used ThinkPad
16,082 MB RAM
Available Physical Memory 4,340 MB
Virtual Memory: Max Size: 21,202 MB
Virtual Memory: Available: 6,123 MB
Virtual Memory: In Use: 15,079 MB