Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger manual Java GC from linux console with no X11

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.

like image 359
Ævar Örn Kvaran Avatar asked Nov 11 '10 14:11

Ævar Örn Kvaran


People also ask

Can you force Java garbage collection?

Unfortunately, this desire to immediately free up memory must go unrequited, as there is no way to force garbage collection (GC) in Java.

Can you manually call the garbage collector 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().

What triggers JVM 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.

How do you force an object to be garbage collected?

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.


3 Answers

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!

like image 179
Andrzej Doyle Avatar answered Oct 11 '22 11:10

Andrzej Doyle


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.

like image 37
arya Avatar answered Oct 11 '22 12:10

arya


jcmd <pid> GC.run

Example:

jcmd 20350 GC.run
like image 32
helder.vasc Avatar answered Oct 11 '22 10:10

helder.vasc