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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button