stop - Get a List of all Threads currently running in Java




stop all running threads java (8)

ManagementFactory.getThreadMXBean().getAllThreadIds()

Is there any way I can get a list of all the running Threads in the current JVM (including the Threads NOT started by my class)?

Is it also possible to get the Thread and Class objects of all Thread in the list?

I want to be able to do this through code.


Apache commons users can use ThreadUtils. The current implementation uses the walk the thread group approach previously outlined.

for (Thread t : ThreadUtils.getAllThreads()) {
      System.out.println(t.getName() + ", " + t.isDaemon());
}

Get a handle to the root ThreadGroup, like this:

ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
ThreadGroup parentGroup;
while ((parentGroup = rootGroup.getParent()) != null) {
    rootGroup = parentGroup;
}

Now, call the enumerate() function on the root group repeatedly. The second argument lets you get all threads, recursively:

Thread[] threads = new Thread[rootGroup.activeCount()];
while (rootGroup.enumerate(threads, true ) == threads.length) {
    threads = new Thread[threads.length * 2];
}

Note how we call enumerate() repeatedly until the array is large enough to contain all entries.


Have you taken a look at jconsole?

This will list all threads running for a particular Java process.

You can start jconsole from the JDK bin folder.

You can also get a full stack trace for all threads by hitting Ctrl+Break in Windows or by sending kill pid --QUIT in Linux.


In the java console, hit Ctrl-Break. It will list all threads plus some information about the heap. This won't give you access to the objects of course. But it can be very helpful for debugging anyway.


To get an iterable set:

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();


You can try something like this:

Thread.getAllStackTraces().keySet().forEach((t) -> System.out.println(t.getName() + "\nIs Daemon " + t.isDaemon() + "\nIs Alive " + t.isAlive()));

and you can obviously get more thread characteristic if you need.







jvm