How do you forcefully collect garbage from Shell?

So, I look at the heap with jmap on the remote box, and I want to force garbage collection on it. How do you do this without inserting jvisualvm or jconsole and friends?

I know that you should not practice garbage collection - you just need to understand why the heap is big / growing.

I also understand that System.GC () does not actually force garbage collection - it just tells GC that you want it to happen.

Having said that, is there a way to make this easy? Am I missing some command line application?

+95
java garbage-collection jmap jmx
Aug 19 '10 at 16:17
source share
7 answers

You can do this through the free jmxterm program.

Run it like this:

java -jar jmxterm-1.0-alpha-4-uber.jar 

From there, you can connect to the host and start the GC:

 $>open host:jmxport #Connection to host:jmxport is opened $>bean java.lang:type=Memory #bean is set to java.lang:type=Memory $>run gc #calling operation gc of mbean java.lang:type=Memory #operation returns: null $>quit #bye 

See the docs on the jmxterm website for information on implementing this in a bash / perl / ruby ​​/ other script. I used popen2 in Python or open3 in Perl to do this.

UPDATE: here is one liner using jmxterm:

 echo run -b java.lang:type=Memory gc | java -jar jmxterm-1.0-alpha-4-uber.jar -n -l host:port 
+22
Aug 19 '10 at 16:33
source share

Starting with JDK 7, you can use the JDK command "jcmd", for example:

jcmd <pid> GC.run

+312
Jan 15 '14 at 14:10
source share

If you run jmap -histo:live , this will result in a full GC on the heap before it prints anything.

+100
Aug 19 '10 at 16:39
source share

There are several more solutions (there are already many good ones):

  • Write a short code to access MemoryMBean and call gc() .
  • Use the command line client JMX client (e.g. cmdline-jmxclient , jxmterm ) and perform the gc() operation on MemoryMBean

The following example is for cmdline-jmxclient:

 $ java -jar cmdline-jmxclient-0.10.3.jar - localhost:3812 'java.lang:type=Memory' gc 

This is good because it is only one line and you can easily place it in a script.

+6
Aug 19 '10 at 16:37
source share

I do not think there is any command line option for this.

You will need to use jvisualvm / jconsole for this.

I would prefer you to use these tools to identify why your program is high in memory.

In any case, you should not force the GC, as this will certainly violate the GC algorithm and make your program slow.

0
Aug 19 '10 at 16:30
source share

If you are using jolokia with your application, you can start garbage collection with this command:

 curl http://localhost:8558/jolokia/exec/java.lang:type=Memory/gc 
0
Dec 22 '17 at 19:21
source share

only

 kill -SIGQUIT <PID> 
-9
Jan 17 '13 at 3:05
source share



All Articles