LostKatana
LostKatana

Reputation: 504

List of currently running threads

I was looking for a solution to get the amount of threads running in my program. I ended up with this two solutions from Get a List of all Threads currently running in Java.

Using

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
runningThreads = threadSet.size();

I end up with 75 threads.


Using

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 ];
}
runningThreads = threads.length;

I end up with the exact doubled amount of threads -> 150


I was wondering why the theads are doubled and saw this threads = new Thread[ threads.length * 2 ];.

Why do we multiply with 2 in this method?

EDIT:
Maybe I have malformed my question. Even if it is answered right now I want to correct it. The question is why we multiply with 2 even the size is already big enough and therefor get the wrong amount of currently running threads.

Upvotes: 0

Views: 1365

Answers (1)

Wand Maker
Wand Maker

Reputation: 18762

As per documentation of ThreadGroup, the method

public int enumerate(Thread[] list,
            boolean recurse)

will recursively enumerate the subgroups. However, it only returns as many threads that can be filled in list argument. So, the code tries to allocate more size to list if it observes that you have received exactly length elements in the list with the assumption that there were more threads to enumerate but array size was not sufficient.

So, when loop terminates, even if you have length elements in the list, last few elements will be null and you will have to ignore them while determining thread count

Upvotes: 2

Related Questions