OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

Is it possible to force immediate garbage collection in Java?

MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.

Is it possible to force immediate garbage collection in Java?

Choose one option.
Show answer & explanation
Answer: A. No, it is non-deterministic even when requesting System.gc()

While System.gc() is a legal method that requests garbage collection, it is non-deterministic—the JVM is not required to honor the request or execute it immediately. The Java Language Specification explicitly states that System.gc() is only a hint to the garbage collector; the actual timing and execution are determined by the JVM implementation. Therefore, you cannot force immediate garbage collection in Java.

Step-by-step Derivation:
Analysis of each option:

  • Option A (Correct): System.gc() exists and is legal, but the JVM may ignore it or defer collection. Garbage collection timing is non-deterministic and implementation-dependent.
  • Option B (Incorrect): System.gc() is absolutely legal to call; there is no restriction on invoking it.
  • Option C (Incorrect): While System.gc() exists, it does not force immediate collection. It is merely a request that the JVM can choose to ignore.
  • Option D (Incorrect): Deleting/nullifying references does not trigger garbage collection; it only makes objects eligible for collection when the GC runs.

Key Concept: Java garbage collection is non-deterministic by design. The programmer cannot force immediate collection—only request it via System.gc(), which the JVM may or may not honor immediately.