Some of you probably know that some of core java APIs make explicit calls to System.gc(). I know two cases when this happens:
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.
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();
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.