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 !

3 answers

  • answered 2018-05-16 05:50 Pankaj Gadge

    You can write your custom implementation for this like

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

  • answered 2018-05-16 05:51 Amit Bera

    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.

  • answered 2018-05-16 05:51 TheLostMind

    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