So I am looking at a heap with jmap on a remote box and I want to force garbage collection on it. How do you do this without popping into jvisualvm or jconsole and friends?
I know you shouldn't be in the practice of forcing garbage collection -- you should just figure out why the heap is big/growing.
I also realize the System.GC() doesn't actually force garbage collection -- it just tells the GC that you'd like it to occur.
Having said that is there a way to do this easily? Some command line app I'm missing?
If you run
jmap -histo:live
, that will force a full GC on the heap before it prints anything out.You can do this via the free jmxterm program.
Fire it up like so:
From there, you can connect to a host and trigger GC:
Look at the docs on the jmxterm web site for information about embedding this in bash/perl/ruby/other scripts. I've used popen2 in Python or open3 in Perl to do this.
UPDATE: here's a one-liner using jmxterm:
Addition to user3198490's answer. Running this command might give you the following error message:
This can be solved with help of this stackoverflow answer
where
<process_owner>
is the user that runs the process with PID<pid>
. You can get both fromtop
orhtop
There's a few other solutions (lots of good ones here already):
gc()
.gc()
operation on the MemoryMBeanThe following example is for the cmdline-jmxclient:
This is nice because it's only one line and you can put it in a script really easily.
Since JDK 7 you can use the JDK command tool 'jcmd' such as:
jcmd <pid> GC.run
just: