Skip to content

Instantly share code, notes, and snippets.

@gonewest818
Last active February 28, 2020 15:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gonewest818/bfa37a77a1967eadc838f6938701efa8 to your computer and use it in GitHub Desktop.
Save gonewest818/bfa37a77a1967eadc838f6938701efa8 to your computer and use it in GitHub Desktop.
getting thread stats via jmx in clojure
(ns xyz.core
(:require [clojure.string :refer [lower-case]])
(:import java.lang.management.ManagementFactory))
(defn describe-thread
"describe thread based on thread-info"
[thread-mx-bean thread-info]
(let [id (.getThreadId thread-info)]
{:id id
:name (.getThreadName thread-info)
:state (-> thread-info .getThreadState .toString lower-case keyword)
:blocked-count (.getBlockedCount thread-info)
:blocked-time (.getBlockedTime thread-info)
:waited-count (.getWaitedCount thread-info)
:waited-time (.getWaitedTime thread-info)
:cpu-time (.getThreadCpuTime thread-mx-bean id)
:user-time (.getThreadUserTime thread-mx-bean id)}))
(defn thread-top
"list all threads sorted by cpu"
[]
(if-let [mx (ManagementFactory/getThreadMXBean)]
(let [thread-dump (.dumpAllThreads mx false false)
thread-info (map (partial describe-thread mx) thread-dump)]
(reverse (sort-by :cpu-time thread-info)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment