0

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.

Community
  • 1
  • 1
LostKatana
  • 468
  • 9
  • 22
  • 3
    I don't know, it's your method. You tell us. EDIT: Ah, I see it's from the referenced answer. Looks like it's to expand the array's capacity. – Thorn G Jul 09 '13 at 13:50

1 Answers1

2

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

Wand Maker
  • 18,476
  • 8
  • 53
  • 87