When does System.gc() do something?

后端 未结 16 1898
傲寒
傲寒 2020-11-22 05:02

I know that garbage collection is automated in Java. But I understood that if you call System.gc() in your code that the JVM may or may not decide to perform ga

相关标签:
16条回答
  • 2020-11-22 05:52

    If you use direct memory buffers, the JVM doesn't run the GC for you even if you are running low on direct memory.

    If you call ByteBuffer.allocateDirect() and you get an OutOfMemoryError you can find this call is fine after triggering a GC manually.

    0 讨论(0)
  • 2020-11-22 05:54

    Normally, the VM would do a garbage collection automatically before throwing an OutOfMemoryException, so adding an explicit call shouldn't help except in that it perhaps moves the performance hit to an earlier moment in time.

    However, I think I encountered a case where it might be relevant. I'm not sure though, as I have yet to test whether it has any effect:

    When you memory-map a file, I believe the map() call throws an IOException when a large enough block of memory is not available. A garbage collection just before the map() file might help prevent that, I think. What do you think?

    0 讨论(0)
  • 2020-11-22 05:55

    You need to be very careful if you call System.gc(). Calling it can add unnecessary performance issues to your application, and it is not guaranteed to actually perform a collection. It is actually possible to disable explicit System.gc() via the java argument -XX:+DisableExplicitGC.

    I'd highly recommend reading through the documents available at Java HotSpot Garbage Collection for more in depth details about garbage collection.

    0 讨论(0)
  • 2020-11-22 05:57

    In practice, it usually decides to do a garbage collection. The answer varies depending on lots of factors, like which JVM you're running on, which mode it's in, and which garbage collection algorithm it's using.

    I wouldn't depend on it in your code. If the JVM is about to throw an OutOfMemoryError, calling System.gc() won't stop it, because the garbage collector will attempt to free as much as it can before it goes to that extreme. The only time I've seen it used in practice is in IDEs where it's attached to a button that a user can click, but even there it's not terribly useful.

    0 讨论(0)
提交回复
热议问题