Reputation: 702
Is there a way to get the count of active daemon threads running in java ?
I used, Thread.getAllStackTraces().keySet().size()
but it did not give the correct result.
This question has reference to the count of daemon threads but it did not have any code for the same.
Could some one please help me on this or any reference on this would also be of great help.
Thanks in advance !
Upvotes: 1
Views: 916
Reputation: 7325
I think you can use ThreadMXBean#getDaemonThreadCount()
API which returns the current number of live daemon threads.
ManagementFactory.getThreadMXBean().getDaemonThreadCount();
For more info please follow the link.
Upvotes: 2
Reputation: 2814
You can write your custom implementation for this like
int daemonThreadCount = 0;
for (Thread thread : Thread.getAllStackTraces().keySet()) {
if (thread.isDaemon()) {
daemonThreadCount++;
}
}
Upvotes: 1
Reputation: 36304
You can do it via Thread.getAllStackTraces
:
public static void main(String[] args) {
Set<Thread> threads = Thread.getAllStackTraces().keySet();
threads.forEach(t -> {
System.out.println(t.getName()+ " : " + t.isDaemon()); // count if isDaemon is true
});
}
O/P :
Signal Dispatcher : true
main : false
Finalizer : true
Reference Handler : true
Upvotes: 3