Interview Q&A / Java

BeginnerQuick answer1 min readUpdated 3 Oct 2026

Does calling System.gc() force garbage collection in Java?

SHORT ANSWER

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

java
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 guaranteed

What 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().

#java#jvm#garbage-collection

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.