Home > Tutorial > Java Thread Stats Sample Code

Java Thread Stats Sample Code

I make use of threads and thread pools in my Java applications and I like to see what threads are currently running and what they are doing. I created this small code snippet that I call periodically using the Java ScheduledExecutorService to log the current thread stats of my Java runtime environment.

The sample code below prints out the thread name, thread state, and the threadgroup it belongs to. Having this log the thread stats periodically helps me to see if the number of threads I am creating is growing, which could indicate a problem.

Java Thread Stats Source Code:

package com.jcd.java.tutorials;

import java.util.Set;

public class JavaThreadStats 
{

	public static void main(String[] args) 
	{

		int threadCtr = 0;
		
		//Get a Map of all thread stack traces
		Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
		
		System.out.println("Thread Statistics:\n");
		
		//Loop each thread in the set
        for ( Thread t : threadSet)
        {
        	System.out.println("Thread Name: "+t.getName()+" State: "+t.getState()+" Group: "+t.getThreadGroup());
            threadCtr++;
        }
        
        System.out.println("\nThread Count: "+threadCtr);

	}

}



Sample Java Thread Stats Output:

Thread Statistics:

Thread Name: Attach Listener State: RUNNABLE Group: java.lang.ThreadGroup[name=system,maxpri=10]
Thread Name: Reference Handler State: WAITING Group: java.lang.ThreadGroup[name=system,maxpri=10]
Thread Name: Signal Dispatcher State: RUNNABLE Group: java.lang.ThreadGroup[name=system,maxpri=10]
Thread Name: main State: RUNNABLE Group: java.lang.ThreadGroup[name=main,maxpri=10]
Thread Name: Finalizer State: WAITING Group: java.lang.ThreadGroup[name=system,maxpri=10]

Thread Count: 5



References:

Smedley
Posted by

Smedley

Smedley has been programming in Java for about twenty years. He enjoys sharing code samples to other fellow Java coders.

You may also like...

(1) Comment

  1. Steve

    This is a nice piece of code for putting out stats on threads. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot