|
5 | 5 | import io.prometheus.client.GaugeMetricFamily; |
6 | 6 |
|
7 | 7 | import java.lang.management.ManagementFactory; |
| 8 | +import java.lang.management.ThreadInfo; |
8 | 9 | import java.lang.management.ThreadMXBean; |
9 | 10 | import java.util.ArrayList; |
| 11 | +import java.util.Collections; |
| 12 | +import java.util.HashMap; |
10 | 13 | import java.util.List; |
| 14 | +import java.util.Map; |
11 | 15 |
|
12 | 16 | /** |
13 | 17 | * Exports metrics about JVM thread areas. |
@@ -73,6 +77,40 @@ void addThreadMetrics(List<MetricFamilySamples> sampleFamilies) { |
73 | 77 | "jvm_threads_deadlocked_monitor", |
74 | 78 | "Cycles of JVM-threads that are in deadlock waiting to acquire object monitors", |
75 | 79 | nullSafeArrayLength(threadBean.findMonitorDeadlockedThreads()))); |
| 80 | + |
| 81 | + GaugeMetricFamily threadStateFamily = new GaugeMetricFamily( |
| 82 | + "jvm_threads_state", |
| 83 | + "Current count of threads by state", |
| 84 | + Collections.singletonList("state")); |
| 85 | + |
| 86 | + Map<Thread.State, Integer> threadStateCounts = getThreadStateCountMap(); |
| 87 | + for (Map.Entry<Thread.State, Integer> entry : threadStateCounts.entrySet()) { |
| 88 | + threadStateFamily.addMetric( |
| 89 | + Collections.singletonList(entry.getKey().toString()), |
| 90 | + entry.getValue() |
| 91 | + ); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + private Map<Thread.State, Integer> getThreadStateCountMap() { |
| 96 | + // Get thread information without computing any stack traces |
| 97 | + ThreadInfo[] allThreads = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 0); |
| 98 | + |
| 99 | + // Initialize the map with all thread states |
| 100 | + HashMap<Thread.State, Integer> threadCounts = new HashMap<Thread.State, Integer>(); |
| 101 | + for (Thread.State state : Thread.State.values()) { |
| 102 | + threadCounts.put(state, 0); |
| 103 | + } |
| 104 | + |
| 105 | + // Collect the actual thread counts |
| 106 | + for (ThreadInfo curThread : allThreads) { |
| 107 | + if (curThread != null) { |
| 108 | + Thread.State threadState = curThread.getThreadState(); |
| 109 | + threadCounts.put(threadState, threadCounts.get(threadState) + 1); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + return threadCounts; |
76 | 114 | } |
77 | 115 |
|
78 | 116 | private static double nullSafeArrayLength(long[] array) { |
|
0 commit comments