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.