-1

Why we are calling System.gc() method to garbage collection of unused object, if garbage collection is automatically done in Java by daemon thread in background process with regular interval?

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
Anu
  • 573
  • 1
  • 5
  • 4
  • 2
    Who's 'we'? You might want to read this thread, and the code in question might be following bad practices or makes some assumptions - ask the person who put it in there why he did it: http://stackoverflow.com/questions/2414105/why-is-it-a-bad-practice-to-call-system-gc – wkl Oct 20 '11 at 16:37
  • 1
    No, *we* don't. The GC runs only when JVM runs out of memory and needs to get rid of, well, garbage. It does not run on regular intervals. – Tomasz Nurkiewicz Oct 20 '11 at 16:42

4 Answers4

4

For testing purposes it can be useful to know when a GC has been performed. However this is rare and calling System.gc() when it isn't needed is such a common mistake that you can turn it off with -XX:+DisableExplicitGC.

aioobe
  • 413,195
  • 112
  • 811
  • 826
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

We're not, because we're generally not smarter than the GC. Technically, calling it doesn't guarantee it'll run, although in many implementations it does.

Also, it's not necessarily done at regular imtervals, but based on an as-needed basis. Different implementations will start GC based on different criteria.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

System.gc() just gives the garbage collector a hint that this might be a good time for garbage collection, e.g. because a lot of objects aren't used anymore and processing has finished.

It doesn't force the garbage collector to do anything - it just gives a hint.

Only use this once you need to optimze your application (after profiling).

I don't think I have ever seen it in production code so far.

Puce
  • 37,247
  • 13
  • 80
  • 152
0

While it shouldn't be necessary, I had code that thrashed much, much less when I did an explicit System.gc after a very large Map was emptied, just to be refilled again, in a loop. I think without a hint the collector tried minor gcs until it was clear that wouldn't do. Yes, I put it in production. I also put in a comment, just so my colleagues would test rather than blindly remove.

Andrew Lazarus
  • 18,205
  • 3
  • 35
  • 53