Skip to content

Instantly share code, notes, and snippets.

@solveme
Last active September 5, 2022 09:09
Show Gist options
  • Save solveme/28f4f231601d85bde23d45b7a089af08 to your computer and use it in GitHub Desktop.
Save solveme/28f4f231601d85bde23d45b7a089af08 to your computer and use it in GitHub Desktop.
Print most CPU consuming threads in descending order for selected Java process (./cpu_consumers.sh | tee consumers.txt)
#!/bin/bash
function print_lwp_line() {
local pid="${1}"
local lwp="${2}"
local nlwp="${3}"
local ruser="${4}"
local pcpu="${5}"
local cputimes="${6}"
local lwp_name="${7}"
printf "%8s %8s %5s %10s %8s %8s %s\n" ${pid} ${lwp} ${nlwp} ${ruser} ${pcpu} ${cputimes} "${lwp_name}"
}
readarray -t processes < <(jps -l)
echo "Choose java process:" >&2
for process_index in ${!processes[@]}; do
pid=$( echo ${processes[process_index]} | cut -d ' ' -f 1)
class=$( echo ${processes[process_index]} | cut -d ' ' -f 2)
printf "%3s %8s %s\n" "${process_index})" "${pid}" "${class}" >&2
done
while :; do
read -r -p "Enter process choice: " chosen_process_index
[[ -z "${chosen_process_index}" ]] && break
[[ -n "${processes[chosen_process_index]}" ]] && break
done
target_pid="$( echo ${processes[chosen_process_index]} | cut -d ' ' -f 1)"
target_class="$( jps | grep ${target_pid} | cut -d ' ' -f 2)"
target_cmd="$(jps -lvm | grep ${target_pid} | sed 's/ -/\n-/g' | sort )"
target_td="${target_class}.${target_pid}.dat"
jstack ${target_pid} > ${target_td}
echo -e "\n${target_cmd}\n"
print_lwp_line "PID" "LWP" "NLWP" "ruser" "CPU[%]" "CPU[s]" "thread_name"
ps -Leo pid,lwp,nlwp,ruser,pcpu,cputimes | grep ${target_pid} | sort -r -k 5 | while read line; do
lwp=$( echo ${line} | awk '{print $2}' )
hex_lwp=$(printf '%x' ${lwp})
lwp_name=$( grep "nid=0x${hex_lwp}" ${target_td} | sed 's/" .*$//' | sed 's/"//g')
print_lwp_line ${line} "${lwp_name}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment