Is there any way I can get a list of all running threads in the current JVM (including the threads not started by my class)?
Is it also possible to get the
In Groovy you can call private methods
// Get a snapshot of the list of all threads
Thread[] threads = Thread.getThreads()
In Java, you can invoke that method using reflection provided that security manager allows it.
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.
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());
}
To get a list of threads and their full states using the terminal, you can use the command below:
jstack -l <PID>
Which <PID>
is the id of process running on your computer. To get the process id of your java process you can simply run the jps
command.
Also, you can analyze your thread dump that produced by jstack in TDAs (Thread Dump Analyzer) such fastthread or spotify thread analyzer tool.
To get an iterable set:
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();