1. Overview
In this short tutorial, we'll learn how to get all running threads in the current JVM, including the threads not started by our class.
2. Use the Thread Class
The getAllStackTrace() method of the Thread class gives a stack trace of all the running threads. It returns a Map whose keys are the Thread objects, so we can get the key set and simply loop over its elements to get information about the threads.
Let's use the printf() method to make the output more readable:
Set<Thread> threads = Thread.getAllStackTraces().keySet();
System.out.printf("%-15s \t %-15s \t %-15s \t %s\n", "Name", "State", "Priority", "isDaemon");
for (Thread t : threads) {
System.out.printf("%-15s \t %-15s \t %-15d \t %s\n", t.getName(), t.getState(), t.getPriority(), t.isDaemon());
}
The output will look like:
Name State Priority isDaemon
main RUNNABLE 5 false
Signal Dispatcher RUNNABLE 9 true
Finalizer WAITING 8 true
Reference Handler WAITING 10 true
As we see, besides thread main, which runs the main program, we have three other threads. This result may vary with different Java versions.
Let's learn a bit more about these other threads:
- Signal Dispatcher: this thread handles signals sent by the operating system to the JVM.
- Finalizer: this thread performs finalizations for objects that no longer need to release system resources.
- Reference Handler: this thread puts objects that are no longer needed into the queue to be processed by the Finalizer thread.
All these threads will be terminated if the main program exits.
3. Use the ThreadUtils Class from Apache Commons
We can also use the ThreadUtils class from Apache Commons Lang library to achieve the same goal:
Let's add a dependency to our pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
And simply use the getAllThreads() method to get all running threads:
System.out.printf("%-15s \t %-15s \t %-15s \t %s\n", "Name", "State", "Priority", "isDaemon");
for (Thread t : ThreadUtils.getAllThreads()) {
System.out.printf("%-15s \t %-15s \t %-15d \t %s\n", t.getName(), t.getState(), t.getPriority(), t.isDaemon());
}
The output is the same as above.
4. Conclusion
In summary, we've learned two methods to get all running threads in the current JVM.