How to know all threads that are currently running in the Java virtual machine? If you are curious, the Thread class provides a static method which can be used to list all active threads. Here’s the method:
static Map<Thread,StackTraceElement[]> getAllStackTraces()
This method returns a map with keys are the Thread objects, so we can get only the key set and iterate over its elements:
Set<Thread> threads = Thread.getAllStackTraces().keySet(); for (Thread t : threads) { // do something with each thread }
The following code snippet will list all threads that are currently running in the JVM along with their information like name, state, priority, and daemon status:
Set<Thread> threads = Thread.getAllStackTraces().keySet(); for (Thread t : threads) { String name = t.getName(); Thread.State state = t.getState(); int priority = t.getPriority(); String type = t.isDaemon() ? "Daemon" : "Normal"; System.out.printf("%-20s \t %s \t %d \t %s\n", name, state, priority, type); }
If you put this code snippet in a console program, the output would be something like this:
Finalizer WAITING 8 Daemon Attach Listener RUNNABLE 5 Daemon Signal Dispatcher RUNNABLE 9 Daemon Reference Handler WAITING 10 Daemon main RUNNABLE 5 Normal
You see, besides the main thread which runs the main program, there are 4 other threads - which are core and default threads necessary to run the JVM. Let’s understand these threads a little bit more:
All of these core threads are daemon. They will be terminated if the main program exits.
In case you put the list threads code in a Swing program, there are more threads:
Attach Listener RUNNABLE 5 Daemon main RUNNABLE 5 Normal AWT-EventQueue-0 RUNNABLE 6 Normal Finalizer WAITING 8 Daemon Signal Dispatcher RUNNABLE 9 Daemon Reference Handler WAITING 10 Daemon Java2D Disposer WAITING 10 Daemon AWT-Windows RUNNABLE 6 Daemon AWT-Shutdown WAITING 5 Normal
As you can see, besides the core threads, there are threads necessary for running the graphical user interface:
And in case you put the list threads code snippet in a servlet running on an application server e.g. Tomcat, the list of threads would be longer like this:
http-nio-8080-ClientPoller-1 RUNNABLE 5 Daemon Finalizer WAITING 8 Daemon main RUNNABLE 5 Normal Reference Handler WAITING 10 Daemon http-nio-8080-ClientPoller-0 RUNNABLE 5 Daemon ajp-nio-8009-Acceptor-0 RUNNABLE 5 Daemon Signal Dispatcher RUNNABLE 9 Daemon http-nio-8080-exec-1 WAITING 5 Daemon http-nio-8080-Acceptor-0 RUNNABLE 5 Daemon http-nio-8080-exec-2 RUNNABLE 5 Daemon ajp-nio-8009-ClientPoller-0 RUNNABLE 5 Daemon ajp-nio-8009-ClientPoller-1 RUNNABLE 5 Daemon NioBlockingSelector.BlockPoller-1 RUNNABLE 5 Daemon GC Daemon TIMED_WAITING 2 Daemon NioBlockingSelector.BlockPoller-2 RUNNABLE 5 Daemon Attach Listener RUNNABLE 5 Daemon
As you can see, most of the additional threads are spawned by the server for handling HTTP requests/responses.