开发者

System.gc() calls by core APIs

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 开发者_StackOverflowdo 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();


I don't understand why they ever even exposed the gc() method. Even in the documentation, Java is pretty clear on the fact that the behavior is unpredictable. The doc says

"Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects"

Meaning, it could do any number of things, including nothing.

As for the question, a lot of application servers call the System.gc() here and there. WebSphere is a prime offender and you can find it all over the WAS/Portal codebase. Haven't seen it in open-source libraries/frameworks that I can remember. Possibly the people who make the effort to contribute to these frameworks have enough sense to not use operations with undefinable behavior.

My guess is that it's being invoked at times when the developer felt that "this operation may, under some circumstances, use a lot of "temporary" (short-lived) memory in processing, so I'll do some garbage collection to reclaim it". This is probably the case for your RMI scenario as well. In my opinion, it's bogus. In some cases, calling System.gc() can LOWER performance by triggering full GC cycles prematurely (and unnecessarily). Point being, the garbage collector is pretty smart and unless you're certain you know better, don't try to mess with it.


A JDK implementation knows exactly how its own System.gc() behaves. JDK does not have to pretend to be agnostic, restraining itself to the standard abstract behavior, instead of the concrete proprietary behavior (which is of course compliant with the standard behavior)

Yes, it can call System.gc() as it sees fit. We shouldn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜