Get a list of all threads currently running in Java
Solution 1
To get an iterable set:
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Performance: 0 ms for 12 threads (Azul JVM 16.0.1, Windows 10, Ryzen 5600X).
Solution 2
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.
Solution 3
Yes, take a look at getting a list of threads. Lots of examples on that page.
That's to do it programmatically. If you just want a list on Linux at least you can just use this command:
kill -3 processid
and the VM will do a thread dump to stdout.
Solution 4
You can get a lot of information about threads from the ThreadMXBean.
Call the static ManagementFactory.getThreadMXBean() method to get a reference to the MBean.
Solution 5
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.
Related videos on Youtube
Kryten
Updated on June 30, 2021Comments
-
Kryten almost 3 years
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
Thread
andClass
objects of all threads in the list?I want to be able to do this through code.
-
Kryten over 14 yearsI want to access the list within my java class
-
pjp over 14 yearsIn which case look at cletus' answer.
-
Michael H. over 14 yearskill -3? At least on my linux, that's "terminal quit". Kills, does not list.
-
Lordn__n over 14 yearsUm, why are people voting this up when the guy said he wanted a programmatic solution?
-
pjp over 14 yearsBecause the question doesn't state that. I'll edit the question to make it explicit.
-
thejoshwolfe almost 13 yearsI'm shocked that this strategy is so popular on the internet. My strategy is way simpler (1 line of code) and works just as well with the added bonus of avoiding race conditions.
-
Eddie over 12 yearsWhile much cleaner than the other alternative proposed, this has the downside of incurring the cost of getting stack traces for all threads. If you will be using those stack traces anyway, this is clearly superior. If not, then this may be significantly slower for no gain other than clean code.
-
thejoshwolfe over 12 years@Eddie Is that an assumption from common sense, or did you do experiments? "significantly slower" you say; how much slower? Is it worth it? I question any attempt to make code worse for the sake of efficiency. If you have an efficiency requirement and an infrastructure to measure efficiency quantitatively, then I'm ok with people making code worse, because they seem to know what they're doing. See the root of all evil according to Donald Knuth.
-
Eddie over 12 yearsI haven't timed these specific alternatives, but I've worked with other Java means of gathering stack traces vs just a list of threads. The performance impact seems to depend very strongly on which JVM you are using (JRockit vs Sun JVM for example). It's worth measuring in your specific instance. Whether or not it will affect you depends on your JVM choice and on how many threads you have. I found that getting all stack traces via ThreadMXBean.dumpAllThreads for about 250 threads to take 150 - 200 msec while getting just the list of threads (without traces) to not be measurable (0 msec).
-
Frerich Raabe over 11 years@thejoshwolfe: Actually, I agree - I think your answer is much better, and it probably would've been the accepted answer in the first place if it wouldn't have been one year late. If the OP still frequents SO, which he apparently does, he'd be well advised to un-accept my answer and rather accept yours.
-
Dan Hardiker about 10 yearscletus is indeed correct - a kill -3 will thread dump to stdout, regardless of what the signal is supposed to mean. I would consider using jstack instead.
-
jmiserez almost 10 yearsNote that for anything other than the
rootGroup
, you should usenew Thread[rootGroup.activeCount()+1]
.activeCount()
could be zero, and if it is you will run into an infinite loop. -
Haozhun over 9 years@thejoshwolfe I suppose this solution is much less expensive.
-
Franz D. about 9 years+1 for this underrated answer, as it is much more suited for monitoring purposes IMHO. Its inherent race conditions do not matter much in monitoring. However, as some quick'n'dirty test showed, it's about 70-80 times faster than the stacktrace-based solution. For monitoring, a small performance imprint is essential, as you you'll want to keep the effects on the monitored system as small as possible (Heisenberg strikes again :) For debugging, where you may need more reliable information, the stacktrace method could be essential. BTW, the MxBean solution is even slower than using stacktraces.
-
Franz D. about 9 yearsOn my system (Oracle Java 1.7 VM), a quick check shows that this method is ~70..80 times SLOWER than the alternative below. Stack traces and reflection belong to the heaviest Java operations.
-
thejoshwolfe about 9 years@FranzD., thanks for doing the research. This strategy may not be suitable for all applications, but don't forget about other factors when comparing code. For example, this code that is arguably easier to read and write than a more performant solution. Also, don't forget about the performance penalties built into the Java runtime iteself, such as garbage collection. It may be informative to measure the performance impact in your actual application.
-
Franz D. about 9 years@thejoshwolfe: Of course, readability is an important factor, and one should not micro-optimize etc. However, I did my research while writing a small application performance monitor. For this kind of tool, a minimal performance imprint is essential to get reliable data, so I chose the stacktrace-less method.
-
David Phillips over 8 yearsGetting a stack trace on HotSpot requires all the threads to reach a safepoint. See "VM Operations and Safepoints": openjdk.java.net/groups/hotspot/docs/RuntimeOverview.html
-
Prateek over 6 yearsYou should give more context around you answer to be useful to not only who asked the question, but also anyone else stumbling on the answer.
-
legendmohe almost 6 yearsBeware of that in android 5.0 or 5.1,
Thread.getAllStackTraces()
may cause GC. -
Michael Sims over 5 yearsCan someone comment as to whether or not the stacktrace method returns threads that are currently RUNNING, or does it also include threads that are in a TERMINATED state?
-
Vlad at MockMotor about 5 yearsNo working in my Java 8 standalone web application. I did not dig deep why, but it misses a whole bunch of running threads.
-
Admin over 4 yearsI get error, getThreads not defined for Thread. And I dont see this function in the documentation.
-
Andreas Klein over 4 yearsOne could argue that the authors of
org.apache.commons.lang3.ThreadUtils
opting for this approach overThread.getAllStackTraces()
for itsgetSystemThreadGroup()
and variousfindThreads()
methods, is a rather prominent endorsement of this answer being best practice. -
DSlomer64 almost 4 yearsgetting a list of threads can’t be reached: nadeausoftware.com refused to connect.
-
Arunav Sanyal over 2 yearsI do not agree that the Thread.getAllStackTraces is the right way to go. It asked for set of thread class. While the answer does give that value, it also intermittently get and then throw away stack traces. And it calls the dumpThreads JNI method which has a huge performance penalty, which it does not really need to, since you only need to call the getThreads JNI method in the thread class. This answer is fine for a pre production or test environment but its a bad idea in production and should be actively avoided.
-
Arunav Sanyal over 2 yearsThis gives the thread ids and not instances of the thread class, which is what this question is asking.
-
Jason Lee over 2 yearsPlease be respectful of other opinions and the people who criticize you. Calling other solutions "shocked that this strategy is so popular" and Argument from authority for anyone who points out your downside is not a good way to discuss.
-
Nathan Tuggy over 2 yearsA bit more perf data: 111 threads in a JVM running a Clojure REPL with a multi-threaded app takes 1.14-1.36 ms (95% CI) to enumerate with this method on a 2019 MacBook Pro with AdoptOpenJDK 8.
-
Nathan Tuggy over 2 years(For comparison, the main alternative method executes in 9.57-10.6 µs in the same REPL that still has 111 threads, so close to two orders of magnitude faster.)