How to get the number of threads in a Java process

Viewed 123827

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

11 Answers

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

jconsole <process-id>

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.

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

    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]);
          }
       }
   }

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

$ 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

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.

Related