aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/concurrent/Threads.java
blob: d30750692e96cc7e2a8c586ebcb42b77c3ae4c2f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.concurrent;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author bjorncs
 */
public class Threads {

    private Threads() {}

    /** Returns all threads in JVM */
    public static Collection<Thread> getAllThreads() {
        ThreadGroup root = Thread.currentThread().getThreadGroup();
        ThreadGroup parent;
        while ((parent = root.getParent()) != null) {
            root = parent;
        }
        // The number of threads may increase between activeCount() and enumerate()
        Thread[] threads = new Thread[root.activeCount() + 100];
        int count;
        while ((count = root.enumerate(threads, true)) == threads.length) {
            threads = new Thread[threads.length + 1000];
        }
        return List.of(Arrays.copyOf(threads, count));
    }
}