Java Management Extension or JMX framwork provides an easily configurable, scalable, reliable and more or less friendly infrastructure for managing Java application either locally or remotely. The framework introduces the concept of MBeans for real-time management of applications.

MXBean:

An MXBean is a type of MBean that references only a predefined set of data types. In this way, you can be sure that your MBean will be usable by any client, including remote clients, without any requirement that the client have access to model-specific classes representing the types of your MBeans

ThreadMXBean:

The management interface for the thread system of the Java virtual machine.

A Java virtual machine has a single instance of the implementation class of this interface. This instance implementing this interface is an MXBean that can be obtained by calling the ManagementFactory.getThreadMXBean() method or from the platform MBeanServer method.

Using ThreadMXBean we can get information about

  • Dumping all live threads and their stack trace
  • Finding deadlock threads those are waiting to get monitors / ownable synchronizes
  • Thread count for live daemon / non daemon threads
  • If cpu thread time and user thread time and Thread Contention Monitoring supported

So now using ThreadMXBean get thread count, currentThreadCpuTime, currentThreadUserTime

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Day47 {
        public static void main(String[] args) {
            ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
            System.out.println("Thread count is "+threadMXBean.getThreadCount());
            System.out.println("Current Thread CPU time "+TimeUnit.MILLISECONDS.convert(threadMXBean.getCurrentThreadCpuTime(),TimeUnit.NANOSECONDS));
            System.out.println(MessageFormat.format("Current Thread User time {0} ",TimeUnit.MILLISECONDS.convert(threadMXBean.getCurrentThreadUserTime(),TimeUnit.NANOSECONDS));
    
            List<ThreadInfo> threadInfos = List.of(threadMXBean.dumpAllThreads(true, true));
            for (ThreadInfo threadInfo: threadInfos) {
                System.out.println(MessageFormat.format("Thread Name is {0} | Thread id -> {1}",threadInfo.getThreadName(),threadInfo.getThreadId()));
            }
        }
      }

Here getting total thread count running in jvm, current thread cpu time (if JVM supports it) it returns in nano second so using TimeUnit.MILISECONDS.convert() to convert it to Miliseconds also current thread user time. After that dumping all the threads and getting the name and id of the threads.