简体   繁体   中英

Why we are calling System.gc() method to garbage collection of unused object

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?

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.

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.

System.gc() just gives the garbage collector a hint that this might be a good time for garbage collection, eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM