Okay, here are a few different ways to force Java GC.
Perform GC
buttonjmap -histo:live 7544
command where 7544 is the pidjcmd 7544 GC.run
commandSystem.gc();
in your codeRuntime.getRuntime().gc()
; in your codeHere's the dirty little secret. None of these are guaranteed to work. You really can't force Java GC.
The Java garbage collection algos are non-deterministic, and while all of these methods can motivate the JVM to do GC, you can't actually force it. If the JVM has too much going on and a stop-the-world operation is not possible, these commands will either error out, or they will run but GC won't actually happen.
if (input.equalsIgnoreCase("gc")) {
System.gc();
result = "Just some GC.";
}
if (input.equalsIgnoreCase("runtime")) {
Runtime.getRuntime().gc();
result = "Just some more GC.";
}
If you've got a memory leak or object allocation problem, then fix it. Sitting around with your finger on Java Mission Control's Force Java GC
button only kicks the can down the road. Profile your app with Java Flight Recorder, view the results in VisualVM or JMC, and fix the problem. Trying to force Java GC is a fools game.