management
Number of current threads
With this example we are going to demonstrate how to get the number of current threads in a JVM. We are using the ThreadMXBean that is the management interface for the thread system of the Java virtual machine. In short, to get the number of current threads you should:
- Get the managed bean for the thread system of the Java virtual machine, that is the ThreadMXBean, using the
getThreadMXBean()
API method of ManagementFactory. - Use
getThreadCount()
API method of ThreadMXBean. It returns the current number of live threads including both daemon and non-daemon threads.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean; public class ThreadCounter { public static void main(String[] args) { // Get JVM's thread system bean ThreadMXBean bean = ManagementFactory.getThreadMXBean(); // Get the number of current live threads int counter = bean.getThreadCount(); System.out.println("Threads = " + counter); } }
Output:
Threads = 5
This was an example of how to get the number of current threads in Java.