javagarbage-collection

Java garbage collection


Java automatically calls garbage collector, then why we need manual calls for garbage collection? When should use System.gc()


Solution

  • Java automatically calls garbage collector, then why we need manual calls for garbage collection?

    We don't need them. Indeed, in most circumstances calling System.gc() is harmful for application performance. See my answer to "Why is it a bad practice to call system gc" for a detailed explanation.

    When should use System.gc()

    If the application knows it is going into a phase where it has nothing else to do AND the user is unlikely to notice a garbage collection, then maybe it is OK call to System.gc() in an effort to stop the user experiencing GC pauses in the future.

    The downsides include:

    (There can also be legitimate reasons to call System.gc() in unit tests, and during system debugging.)