harshavmb harshavmb - 8 months ago 46
Linux Question

Shell script to take thread dump of a java process


we can take thread dump of a running java process. With
ps -aef | grep java
commands, we can identify the rogue process using most of the system resources.

So, if we use
jstack <rogue pid> >> threaddump.log
we can take the thread dump of the specified java process.

Now my question, is there any shell script that can identify the top java process, take process id(pid), inputs to
utility and take the thread dump?

I've searched online and most of the links need manual efforts of inputting process id. So, I'm just curios to know if there is any existing shell script which can avoid manual input.

Thanks in advance.

Answer Source

For me this pipe works:

ps -eo pid,%cpu,comm | grep java |sort -nr -k2 | head -n1 | awk '{print $1}' | xargs jstack


ps -eo pid,%cpu,comm : prints all processes with PID CPU usage and command name

grep java : greps all java processes

sort -nr -k2 : sorts the result numerical reverse by the second column

head -n1 : prints the first row

awk '{print $1}' : prints the first column

xargs jstack : takes the input and uses it as argument for the jstack command