Wednesday, June 6, 2012



Get a list of all the running Threads in the current JVM and its origination


Sometimes, it makes sense to know the list of all running threads in the JVM. Either when you are creating your own profiling tool, or, when you need to monitor the health of your system and need meta-information of your platform. You may also need the information of all running threads when you would like to selectively, say 'stop' the threads (a technique i would showcase in my subsequent posts).


There are two ways to get it:

1. The long way:


Get the root thread group. and then call the enumerate() function on the root group repeatedly.


ThreadGroup rootGroup = Thread.currentThread( ).getThreadGroup( );
ThreadGroup parentGroup;
while ( ( parentGroup = rootGroup.getParent() ) != null ) {
rootGroup = parentGroup;
}



Thread[] threads = new Thread[ rootGroup.activeCount() ];
while ( rootGroup.enumerate( threads, true ) == threads.length ) {
threads = new Thread[ threads.length * 2 ];
}

for(Thread t : threads)
{
System.out.println("Thread name:"+t.getName());
StackTraceElement[] stackTraceElements = t.getStackTrace();
for(StackTraceElement s: stackTraceElements)
{
System.out.println("class name="+s.getClassName()+" and method name="+s.getMethodName()+" at line no.="+s.getLineNumber() );
}
}


2. The short way:


Set threadSet = Thread.getAllStackTraces().keySet();
//now just for displaying get the threads
threads = threadSet.toArray(new Thread[threadSet.size()]);
for(Thread t : threads)
{
System.out.println("Thread name:"+t.getName());
StackTraceElement[] stackTraceElements = t.getStackTrace();
for(StackTraceElement s: stackTraceElements)
{
System.out.println("class name="+s.getClassName()+" and method name="+s.getMethodName()+" at line no.="+s.getLineNumber() );
}
}




No comments:

Post a Comment