简体   繁体   中英

Daemon Thread Count in Java

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 !

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

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 .

You can write your custom implementation for this like

int daemonThreadCount = 0;
for (Thread thread : Thread.getAllStackTraces().keySet()) {
    if (thread.isDaemon()) {
        daemonThreadCount++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM