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 NormalYou 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:
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
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 DaemonAs you can see, most of the additional threads are spawned by the server for handling HTTP requests/responses.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.