I need a way to be able to trigger full GC from a linux console script on ubuntu. I know this is extremely bad practice but without going into too much detail this keeps my server running, This is only meant for 1 or 2 days while I fix the actual problem, so I don't have to wake up in the night and perform manual GC through jconsole or jvisualvm.
Alternatively I have to make a mouse script that clicks the button every 3-4 hours or so which is even worse.
Please help.
Unfortunately, this desire to immediately free up memory must go unrequited, as there is no way to force garbage collection (GC) in Java.
Whenever you are using garbage collections in Java it is important to note that you can never predict when the garbage collector will run. You can try to explicitly call the garbage collector by System. gc() and Runtime. gc().
When a JVM runs out of space in the storage heap and is unable to allocate any more objects (an allocation failure), a garbage collection is triggered. The Garbage Collector cleans up objects in the storage heap that are no longer being referenced by applications and frees some of the space.
You can force object finalization to occur by calling System 's runFinalization method. System. runFinalization(); This method calls the finalize methods on all objects that are waiting to be garbage collected.
If you can have your application start a JMX server (which I believe is implied from your use of jconsole/jvisualvm), then you can invoke the Memory MBean's gc
operation via command-line utilities.
Firstly you'll need some kind of command-line JMX client. I've used this one in the past for simple command-line invocations and it worked fine. (Edit: In fact I used it just now to test out the following command, and it invoked GC successfully on a local Tomcat process)
Then you'll need to work out the command to trigger garbage collection. I think this should work (you'll of course need to change hosts/ports/credentials as appropriate):
java -jar cmdline-jmxclient-X.X.jar - localhost:8081 java.lang:type=Memory gc
Finally, you can schedule invocation of this command via cron
or equivalent.
Voila!
If you have oracle jvm 1.7, you can use jcmd
to list the jvm PIDs, and then jcmd <pid> GC.run
to GC.
jcmd <pid> help
will show you what other commands are available.
jcmd <pid> GC.run
Example:
jcmd 20350 GC.run
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With