This might be pretty basic, but was very curious to know.
Here’s the code snippet and the output
public class PlainSystemGC {
public static void main(String ...strings) {
System.out.println("Free Memory (Before GC): " + Runtime.getRuntime().freeMemory());
System.gc();
System.out.println("Free Memory (After GC): " + Runtime.getRuntime().freeMemory());
}
}
and the output
Free Memory (Before GC): 1859640
Free Memory (After GC): 1911768
I am interested to know what is GC collecting here since no objects are created.
What’s the memory thats being freed up ? ( and that too 52kb )
@JSauer – It gives Exactly the same results even if run 100 times
On most JVM implementations the
mainmethod is not actually the first piece of Java code that is run during the JVM startup.Usually, many parts of a complete JRE are themselves implemented in Java. For example a big part of the classloader mechanism is implemented in pure Java. It might even be able to write parts of the garbage collection algorithm itself in Java.
Due to this, there may already be some garbage from those system classes that the gc can collect even if your application created no garbage at all.
By the way, your application creates at least one object that is eligible for garbage collection at the point where
System.gc()is called: TheStringthat mentions the free memory is constructed dynamically and not held in a variable, so it could well be gc-ed during theSystem.gc()call.