Java OCA OCP Practice Question 981

Question

How can you force garbage collection of an object?

  • A. Garbage collection cannot be forced.
  • B. Call System.gc().
  • C. Call System.gc(), passing in a reference to the object to be garbage-collected.
  • D. Call Runtime.gc().
  • E. Set all references to the object to null.


A.

Note

Garbage collection cannot be forced.

B and D are incorrect. Calling System.gc() or Runtime.gc() is not 100 percent reliable, because the garbage-collection thread might defer to a thread of higher priority.

Option C is incorrect because the two gc() methods do not take arguments.

If you still have a reference to pass into any method, the object is not yet eligible to be collected.

Option E will make the object eligible for collection the next time the garbage collector runs.




PreviousNext

Related