核心 API 调用 System.gc()

2022-01-16 00:00:00 jvm garbage-collection java

Some of you probably know that some of core java APIs make explicit calls to System.gc(). I know two cases when this happens:

  1. NIO. I believe that is done to do some cleanup for direct ByteBuffers, when system runs out of "direct" memory.
  2. RMI. Here, the reason is not that clear for me...

So, questions are:

  1. Do know reason why System.gc() is required for RMI?
  2. Do you know any other situations when core APIs (or even some other popular libraries) can make a direct call to System.gc()?

解决方案

RMI calls the System.gc() in case there are distributed objects which need to be cleaned up. You can make it perform GC less often or effectively turn it off.

You can avoid direct ByteBuffer needing a GC to clean them up on the Sun/Oracle JVM by calling

ByteBuffer bb = ByteBuffer.allocateDirect(SIZE);
((DirectBuffer) bb).cleaner().clean();

相关文章