@@ -129,7 +129,7 @@ private void register(PrometheusRegistry registry) {
129129 .labelNames ("state" )
130130 .callback (
131131 callback -> {
132- Map <String , Integer > threadStateCounts = getThreadStateCountMap ( threadBean );
132+ Map <String , Integer > threadStateCounts = getThreadStateCountMapFromThreadGroup ( );
133133 for (Map .Entry <String , Integer > entry : threadStateCounts .entrySet ()) {
134134 callback .call (entry .getValue (), entry .getKey ());
135135 }
@@ -175,6 +175,49 @@ private Map<String, Integer> getThreadStateCountMap(ThreadMXBean threadBean) {
175175 return threadCounts ;
176176 }
177177
178+ private Map <String , Integer > getThreadStateCountMapFromThreadGroup () {
179+ int threadsNew = 0 ;
180+ int threadsRunnable = 0 ;
181+ int threadsBlocked = 0 ;
182+ int threadsWaiting = 0 ;
183+ int threadsTimedWaiting = 0 ;
184+ int threadsTerminated = 0 ;
185+ int threadsUnknown = 0 ;
186+ ThreadGroup threadGroup = Thread .currentThread ().getThreadGroup ();
187+ Thread [] threads = new Thread [threadGroup .activeCount ()];
188+ threadGroup .enumerate (threads );
189+ for (Thread thread : threads ) {
190+ if (thread == null ) {
191+ // race protection
192+ continue ;
193+ }
194+ switch (thread .getState ()) {
195+ case NEW : threadsNew ++; break ;
196+ case RUNNABLE : threadsRunnable ++; break ;
197+ case BLOCKED : threadsBlocked ++; break ;
198+ case WAITING : threadsWaiting ++; break ;
199+ case TIMED_WAITING : threadsTimedWaiting ++; break ;
200+ case TERMINATED : threadsTerminated ++; break ;
201+ default :
202+ threadsUnknown ++;
203+ }
204+ }
205+
206+ // Initialize the map with all thread states
207+ Map <String , Integer > threadCounts = new HashMap <>();
208+
209+ threadCounts .put (Thread .State .NEW .name (), threadsNew );
210+ threadCounts .put (Thread .State .RUNNABLE .name (), threadsRunnable );
211+ threadCounts .put (Thread .State .BLOCKED .name (), threadsBlocked );
212+ threadCounts .put (Thread .State .WAITING .name (), threadsWaiting );
213+ threadCounts .put (Thread .State .TIMED_WAITING .name (), threadsTimedWaiting );
214+ threadCounts .put (Thread .State .TERMINATED .name (), threadsTerminated );
215+ // Add the thread count for invalid thread ids
216+ threadCounts .put (UNKNOWN , threadsUnknown );
217+
218+ return threadCounts ;
219+ }
220+
178221 private double nullSafeArrayLength (long [] array ) {
179222 return null == array ? 0 : array .length ;
180223 }
0 commit comments