I've written a command line that effectively extracts the highest CPU java PID thread process from top -H (example code):

top -H -n 1 | grep "java" | head -n 1 | cut -d' ' -f1

I want to inspect the PID in jstack. Due to how fast the threads appear and disappear, it's not possible to enter the PID manually, and I was hoping to pipe the result directly into jstack, however whenever one does, for example (simplest code example that reproduces the issue):

12345 | jstack

jstack merely throws up the usage help page, as if pipe isn't sending the variable to jstack.

How can I get the PID I've got with my command into jstack?


jstack expects the process id to be provided as a parameter, so you should use command substitution:

jstack "$(top -H -n 1 | grep "java" | head -n 1 | cut -d' ' -f1)"

You can use ps to find the process instead of filtering top’s output:

jstack "$(ps -C java -o pid --sort %cpu --no-headers | head -n 1)"

This uses ps to find processes whose command matches java, outputs their PID only, sorted by CPU usage, with no headers, and keeps the first one; the result is given to jstack.

To find the thread ID using the most CPU, output tid instead, with the -L option to get ps to process threads:

ps -L -C java -o tid --sort %cpu --no-headers | head -n 2

(I’m extracting the first two because the first will always match the PID, which groups all the CPU usage for the process as a whole).

You can use printf to output that in hexadecimal:

printf "%x\n" $(ps -L -C java -o tid --sort %cpu --no-headers | head -n 2)
  • Using top -H to inspect individual thread processes (as ps lumps all java threads together) as I'm trying to track down individual Java processes that are hogging CPU. Wasn't aware variable substitution was a thing, so thank you for solving my problem! – SSight3 Oct 24 '18 at 13:37
  • I realise you were using top -H, however since you’re extracting the PID from top, not the TID, I didn’t think there would be any practical difference with the ps approach — do you have a scenario where there is? – Stephen Kitt Oct 24 '18 at 13:40
  • Unfortunately, I am not knowledgeable enough to comment. I was attempting to follow (somewhat) the steps detailed here: stackoverflow.com/a/15815829/889894 – SSight3 Oct 24 '18 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.