As I know when I run garbage collection using System.gc() method it will collect all the unused and undestroyed objects from the heap and clean it. So when I run the System.gc(); the memory of the JVM should be increased. but in the below code when I run it, the result is confusing me.
Runtime rs = Runtime.getRuntime();
System.out.println("Free memory in JVM before Garbage Collection = " +
rs.freeMemory());
rs.gc();
System.out.println("Free memory in JVM after Garbage Collection = " +
rs.freeMemory());
the output is
Free memory in JVM before Garbage Collection = 12184624
Free memory in JVM after Garbage Collection = 12184360
see the before value is greater than after value.
Please correct me if I in a wrong concept or explain me why this happen.
Thank you.
Calling for garbage collection in Java is merely a suggestion to the JVM. The way that garbage is collected is technically 100% out of your control. Calling System.gc() politely suggests that the trash should be taken out, but Java is within its rights to ignore you completely like a disobedient child.
Although it will USUALLY do as you ask, it won't always and you certainly can't rely on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With