Java tutorial
//package com.java2s; /* * * The contents of this file are subject to the Terracotta Public License Version * 2.0 (the "License"); You may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://terracotta.org/legal/terracotta-public-license. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Covered Software is Terracotta Core. * * The Initial Developer of the Covered Software is * Terracotta, Inc., a Software AG company * */ import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean; public class Main { protected static final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); protected static volatile ThreadGroup rootThreadGroup; /** * Get all threads. */ public static Thread[] getAllThreads() { final ThreadGroup root = getRootThreadGroup(); int alloc = threadMXBean.getThreadCount(); int size = 0; Thread[] threads; // ThreadGroup.enumerate() will only return as many threads as it can fit in // the array it's given, and we have no accurate way to know how many threads // there will be at the time it is called. do { alloc *= 2; threads = new Thread[alloc]; size = root.enumerate(threads, true); } while (size >= alloc); Thread[] trimmed = new Thread[size]; System.arraycopy(threads, 0, trimmed, 0, size); return trimmed; } public static ThreadGroup getRootThreadGroup() { if (rootThreadGroup == null) { ThreadGroup tg = Thread.currentThread().getThreadGroup(); ThreadGroup parent = tg.getParent(); while (parent != null) { tg = parent; parent = tg.getParent(); } rootThreadGroup = tg; } return rootThreadGroup; } }