[Proposal/Question] Provide mechanism to monitor thread states more efficiently
Christoph Dreis
christoph.dreis at freenet.de
Fri Oct 27 15:23:09 UTC 2017
Hey,
I don't know if this is the correct mailing list for this specific topic.
Please let me know in case it isn't.
I'm currently trying to improve the live-monitoring of an application and
would like to get a simple overview of how many threads are in state
RUNNABLE, BLOCKED and so on.
For this I need to get all threads in the first place to iterate on. I know
of two ways how to do that programmatically:
1) ThreadMXBean.dumpAllThreads() which gives me an array of ThreadInfo
objects on which I could call getThreadState()
2) Thread.getAllStackTraces().keySet() which gives me a Set of Thread
objects on which I could call getState()
Either 1) or 2) both dump the threads, which seems like a lot of overhead
for this task and therefore presumably aren't supposed to be executed every
X seconds. Using reflection to make the private native Thread.getThreads()
available - if that's even possible(?) - doesn't seem correct either. Is
there an alternative for this?
If not, I'd like to suggest the addition of two in my opinion more
lightweight alternative APIs in Thread and/or ThreadMXBean (ThreadImpl).
Here is what I'm thinking of in a rough and untested state:
public static Map<Thread.State, Integer> getAllThreadStateCounts() {
// Get a snapshot of the list of all threads
Thread[] threads = getThreads();
Map<Thread.State, Integer> m = new
EnumMap<>(Thread.State.class);
for (int i = 0; i < threads.length; i++) {
m.merge(threads[i].getState(), 1, Integer::sum);
}
return m;
}
public static int getThreadCountByState(Thread.State state) {
// Get a snapshot of the list of all threads
Thread[] threads = getThreads();
int counter = 0;
for (int i = 0; i < threads.length; i++) {
if (state == threads[i].getState()) {
counter++;
}
}
return counter;
}
Is this something that could be worthwhile? Let me know what you think.
Cheers,
Christoph
More information about the core-libs-dev
mailing list