The only way I know to force garbage collection is to use ForceGarbageCollection() from JVMTI. Is there any cross-platofrm way to force GC (so I don't need to create a JVMTI library for each platform)?
I think that the answer is No.
But I also think that you shouldn't need to do this anyway.
The way to request the garbage collector to run is to call System.gc()
. But as the javadoc explains, this can be ignored.
The normal reason that System.gc()
is ignored is that the JVM has been launched with the option -XX:+DisableExplicitGC
. This is NOT the default. It only happens if the person or script or whatever launching the JVM wants this behavior.
So you are really asking for a way for an application override the user or administrator's explicit instructions to ignore System.gc()
calls. You should not be doing that. It is not the application or the application writer's prerogative to override the user's wishes.
If your Java application really needs to run the GC explicitly, include in the installation instructions that it should NOT be run with the -XX:+DisableExplicitGC
option. Then System.gc()
should work.
So why did they provide a way to disable gc()
calls?
Basically because explicitly running the gc()
is bad practice (see Why is it bad practice to call System.gc()?) and (nearly always1) unnecessary in a properly written application2. If you application relies on the GC running at specific times to function, then you have made a mistake in the application design.
1 - A couple of exceptions are test cases for code that uses Reference
types and similar, and interactive games where you want to (say) clean up between levels to avoid a GC pause during normal play.
2 - It is not uncommon for a Java programmer to start out as a C or C++ programmer. It can be difficult for such people to realize that they don't need to take a hand in Java memory management. The JVM (nearly always) has better understanding of when to run the GC. People also come across Object.finalize
and dream up "interesting" ways to use it ... without realizing that it is an expensive and (ultimately) unreliable mechanism.