Home » Core Java » lang » management » Number of current threads

About Ilias Tsagklis

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

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of