Does calling System.gc() force garbage collection in Java?
No. System.gc() is only a hint, and the JVM may ignore it. Even when it runs, it often triggers an expensive full collection, so production code should not call it.
Explain it simply
Telling the sweeper "please clean the hall now" does not guarantee he will do it right away, and if he does, the whole hall has to be emptied. The JVM treats System.gc() as a polite request.
Example
Runtime rt = Runtime.getRuntime();
long before = rt.totalMemory() - rt.freeMemory();
byte[] big = new byte[50_000_000];
big = null;
System.gc(); // request only; the JVM may or may not collect
long after = rt.totalMemory() - rt.freeMemory();
// 'after' is usually lower than before + 50MB, but not guaranteedWhat to say in the interview
"The specification says System.gc() suggests that the JVM spend effort on collecting unused objects. Implementations may honour it with a full collection, which pauses the application, or ignore it, for instance with -XX:+DisableExplicitGC. Calling it in production is a bad sign. The JVM picks collection times based on allocation pressure. I only see it in benchmarks or tests, and in some old libraries, such as RMI, which call it periodically."
Common mistakes
- Adding System.gc() calls to 'fix' memory problems instead of finding the leak.
- Relying on finalize() to run after System.gc().