0

Can we call the Garbage Collector more than once in a single Java program?

1 Answers1

2

If by "call the Garbage Collector" you mean "invoke System.gc() -- you can do it as often as you like. It may have some effect, or it may have none. Depending on the circumstances, it may make your application perform better, or it may make things worse.

Modern Java implementations are designed to run with completely transparent GC. My experience is that it rarely helps to poke the GC into action although, nearly always, calling gc() does actually elicit some sort of response from the JVM -- it's not usually ignored completely.

I've seen applications that use repeated calls to gc() to overcome bugs in the application (usually related to resource management); or even, very occasionally, bugs in the JVM.

On balance, though, I expect that if you find your application needs to poke the GC often, something is broken and, these days, it's most likely the application.

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15
  • imho: an excellent answer, simple and to the point. `System::gc` is used also for proving some things in tests or sandboxes, for example, too. Like a case when a `WeakReference` is cleared, etc. There are also flags that control what `System::gc` is going to do : `DisableExplicitGC` and `ExplicitGCInvokesConcurrent` – Eugene Sep 30 '20 at 14:44
  • 1
    It doesn’t need to be a “modern Java implementation”. Calling `gc()` manually never was required. – Holger Oct 01 '20 at 08:20
  • @Holger -- in principle, yes. However I can remember having to help out the GC back in the early days of Java. – Kevin Boone Oct 01 '20 at 10:31
  • 1
    When you want to make the stats look good without actually needing the memory. Actual allocations always triggered a gc when no memory was available. That worked in JDK 1.1 for sure. I didn’t test 1.0 enough to say that for sure, though… Well, the only exception is when having lots of objects with a `finalize()` method, though. As garbage collection doesn’t imply finalization, so running gc in advance could make a difference then. – Holger Oct 01 '20 at 10:34