88

How can I see the number of threads in a Java process?

11 Answers 11

97
java.lang.Thread.activeCount()

It will return the number of active threads in the current thread's thread group.

docs: http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#activeCount()

Note from the docs:

The value returned is only an estimate because the number of threads may change dynamically while this method traverses internal data structures, and might be affected by the presence of certain system threads. This method is intended primarily for debugging and monitoring purposes.

1
  • 3
    It is only an estimate.
    – 3xCh1_23
    Jul 5, 2018 at 20:10
88

ManagementFactory.getThreadMXBean().getThreadCount() doesn't limit itself to thread groups as Thread.activeCount() does.

3
  • +1 For this. The amount of thread is exactly the same one i see on top. Although on the debug window, i only see 2 thread running instead of 5. :/
    – Aruman
    Mar 5, 2013 at 10:39
  • ManagementFactory ? under which package ?
    – Meher
    Jan 9, 2014 at 18:47
  • import java.lang.management.ManagementFactory; docs.oracle.com/javase/8/docs/api/java/lang/management/… Also see getPeakThreadCount() and other methods before you start doing it yourself :) Mar 5, 2020 at 10:27
58

Useful tool for debugging java programs, it gives the number of threads and other relevant info on them:

jconsole <process-id>

0
26

There is a static method on the Thread Class that will return the number of active threads controlled by the JVM:

Thread.activeCount()

Returns the number of active threads in the current thread's thread group.

Additionally, external debuggers should list all active threads (and allow you to suspend any number of them) if you wish to monitor them in real-time.

22

Generic solution that doesn't require a GUI like jconsole (doesn't work on remote terminals), ps works for non-java processes, doesn't require a JVM installed.

ps -o nlwp <pid>

11

I have written a program to iterate all Threads created and printing getState() of each Thread

import java.util.Set;

public class ThreadStatus {
    public static void main(String args[]) throws Exception{
        for ( int i=0; i< 5; i++){
            Thread t = new Thread(new MyThread());
            t.setName("MyThread:"+i);
            t.start();
        }
        int threadCount = 0;
        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        for ( Thread t : threadSet){
            if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()){
                System.out.println("Thread :"+t+":"+"state:"+t.getState());
                ++threadCount;
            }
        }
        System.out.println("Thread count started by Main thread:"+threadCount);
    }
}

class MyThread implements Runnable{
    public void run(){
        try{
            Thread.sleep(2000);
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

Output:

java ThreadStatus

Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[main,5,main]:state:RUNNABLE
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:4,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:3,5,main]:state:TIMED_WAITING
Thread count started by Main thread:6

If you remove below condition

if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup())

You will get below threads in output too, which have been started by system.

Reference Handler, Signal Dispatcher,Attach Listener and Finalizer.

8

Using Linux Top command

top -H -p (process id)

you could get process id of one program by this method :

ps aux | grep (your program name)

for example :

ps aux | grep user.py

1
  • top -H -p `pgrep -u <userid here> <program name>` Feb 3, 2022 at 17:53
2
    public class MainClass {

        public static void main(String args[]) {

          Thread t = Thread.currentThread();
          t.setName("My Thread");

          t.setPriority(1);

          System.out.println("current thread: " + t);

          int active = Thread.activeCount();
          System.out.println("currently active threads: " + active);
          Thread all[] = new Thread[active];
          Thread.enumerate(all);

          for (int i = 0; i < active; i++) {
             System.out.println(i + ": " + all[i]);
          }
       }
   }
1

Get number of threads using jstack

jstack <PID> | grep 'java.lang.Thread.State' | wc -l

The result of the above code is quite different from top -H -p <PID> or ps -o nlwp <PID> because jstack gets only threads from created by the application.

In other words, jstack will not get GC threads

1

Another way: Get the process name using jps command and use that in below script snippet:

# Get the process id
processPid=$(jps -l | grep "Process Name" | awk '{print $1}'); 
# Use process id to get number of threads using ps command 
ps -M $processPid| wc -l

Tested on macOS.

0

$ ps -p <pid> -lfT | wc -l

You can get the pid using:

$ top or $ ps aux | grep (your program name)

To get all threads, not only for one process

$ ps -elfT | wc -l

This is for centOS / Red Hat machines, it may or not work on other linux machines

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.