public static void clearThreadLocal(ThreadLocal tl) { ThreadGroup root = Thread.currentThread().getThreadGroup().getParent(); while (root.getParent() != null) { root = root.getParent(); } visit(root, tl, 0); }
private static void visit(ThreadGroup group, ThreadLocal tl, int level) { // Get threads in `group' int numThreads = group.activeCount(); Thread[] threads = new Thread[numThreads * 2]; numThreads = group.enumerate(threads, false); // Enumerate each thread in `group' for (int i = 0; i < numThreads; i++) { Thread thread = threads[i]; clearThreadLocal(tl, thread); } // Get thread subgroups of `group' int numGroups = group.activeGroupCount(); ThreadGroup[] groups = new ThreadGroup[numGroups * 2]; numGroups = group.enumerate(groups, false); // Recursively visit each subgroup for (int i = 0; i < numGroups; i++) { visit(groups[i], tl, level + 1); } }