Skip to content

Commit

Permalink
[Performance]Use threadGroup to compute threads state rather than Thr…
Browse files Browse the repository at this point in the history
…eadMXBean

Signed-off-by: zhanghaobo@kanzhun.com <hfutzhanghb@163.com>
  • Loading branch information
zhanghaobo@kanzhun.com authored and hfutatzhanghb committed Dec 18, 2024
1 parent 21af74e commit b52fff7
Showing 1 changed file with 44 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ private void register(PrometheusRegistry registry) {
.labelNames("state")
.callback(
callback -> {
Map<String, Integer> threadStateCounts = getThreadStateCountMap(threadBean);
Map<String, Integer> threadStateCounts = getThreadStateCountMapFromThreadGroup();
for (Map.Entry<String, Integer> entry : threadStateCounts.entrySet()) {
callback.call(entry.getValue(), entry.getKey());
}
Expand Down Expand Up @@ -175,6 +175,49 @@ private Map<String, Integer> getThreadStateCountMap(ThreadMXBean threadBean) {
return threadCounts;
}

private Map<String, Integer> getThreadStateCountMapFromThreadGroup() {
int threadsNew = 0;
int threadsRunnable = 0;
int threadsBlocked = 0;
int threadsWaiting = 0;
int threadsTimedWaiting = 0;
int threadsTerminated = 0;
int threadsUnknown = 0;
ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
Thread[] threads = new Thread[threadGroup.activeCount()];
threadGroup.enumerate(threads);
for (Thread thread : threads) {
if (thread == null) {
// race protection
continue;
}
switch (thread.getState()) {
case NEW: threadsNew++; break;
case RUNNABLE: threadsRunnable++; break;
case BLOCKED: threadsBlocked++; break;
case WAITING: threadsWaiting++; break;
case TIMED_WAITING: threadsTimedWaiting++; break;
case TERMINATED: threadsTerminated++; break;
default:
threadsUnknown++;
}
}

// Initialize the map with all thread states
Map<String, Integer> threadCounts = new HashMap<>();

threadCounts.put(Thread.State.NEW.name(), threadsNew);
threadCounts.put(Thread.State.RUNNABLE.name(), threadsRunnable);
threadCounts.put(Thread.State.BLOCKED.name(), threadsBlocked);
threadCounts.put(Thread.State.WAITING.name(), threadsWaiting);
threadCounts.put(Thread.State.TIMED_WAITING.name(), threadsTimedWaiting);
threadCounts.put(Thread.State.TERMINATED.name(), threadsTerminated);
// Add the thread count for invalid thread ids
threadCounts.put(UNKNOWN, threadsUnknown);

return threadCounts;
}

private double nullSafeArrayLength(long[] array) {
return null == array ? 0 : array.length;
}
Expand Down

0 comments on commit b52fff7

Please sign in to comment.