本文整理了Java中java.lang.Thread.enumerate()
方法的一些代码示例,展示了Thread.enumerate()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Thread.enumerate()
方法的具体详情如下:
包路径:java.lang.Thread
类名称:Thread
方法名:enumerate
[英]Copies into the specified array every active thread in the current thread's thread group and its subgroups. This method simply invokes the java.lang.ThreadGroup#enumerate(Thread[])method of the current thread's thread group.
An application might use the #activeCountmethod to get an estimate of how big the array should be, however if the array is too short to hold all the threads, the extra threads are silently ignored. If it is critical to obtain every active thread in the current thread's thread group and its subgroups, the invoker should verify that the returned int value is strictly less than the length of tarray.
Due to the inherent race condition in this method, it is recommended that the method only be used for debugging and monitoring purposes.
[中]将当前线程的线程组及其子组中的每个活动线程复制到指定数组中。此方法只调用java。lang.ThreadGroup#枚举当前线程的线程组的(Thread[])方法。
应用程序可能会使用#activeCountmethod来估计数组应该有多大,但是如果数组太短,无法容纳所有线程,那么额外的线程将被静默忽略。如果获取当前线程的线程组及其子组中的每个活动线程非常关键,那么调用程序应该验证返回的int值是否严格小于tarray的长度。
由于此方法中固有的竞争条件,建议仅将此方法用于调试和监视目的。
代码示例来源:origin: apache/ignite
/**
* @param threadId Thread ID.
* @return Thread name if found.
*/
public static String threadName(long threadId) {
Thread[] threads = new Thread[Thread.activeCount()];
int cnt = Thread.enumerate(threads);
for (int i = 0; i < cnt; i++)
if (threads[i].getId() == threadId)
return threads[i].getName();
return "<failed to find active thread " + threadId + '>';
}
代码示例来源:origin: objectbox/objectbox-java
/** dump thread stacks if pool does not terminate promptly. */
private void checkThreadTermination() {
try {
if (!threadPool.awaitTermination(1, TimeUnit.SECONDS)) {
int activeCount = Thread.activeCount();
System.err.println("Thread pool not terminated in time; printing stack traces...");
Thread[] threads = new Thread[activeCount + 2];
int count = Thread.enumerate(threads);
for (int i = 0; i < count; i++) {
System.err.println("Thread: " + threads[i].getName());
Thread.dumpStack();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
代码示例来源:origin: AsyncHttpClient/async-http-client
private static Thread[] getThreads() {
int count = Thread.activeCount() + 1;
for (; ; ) {
Thread[] threads = new Thread[count];
int filled = Thread.enumerate(threads);
if (filled < threads.length) {
return Arrays.copyOf(threads, filled);
}
count *= 2;
}
}
代码示例来源:origin: ben-manes/caffeine
/**
* Finds missing try { ... } finally { joinPool(e); }
*/
void checkForkJoinPoolThreadLeaks() throws InterruptedException {
Thread[] survivors = new Thread[5];
int count = Thread.enumerate(survivors);
for (int i = 0; i < count; i++) {
Thread thread = survivors[i];
String name = thread.getName();
if (name.startsWith("ForkJoinPool-")) {
// give thread some time to terminate
thread.join(LONG_DELAY_MS);
if (!thread.isAlive()) {
continue;
}
thread.stop();
throw new AssertionFailedError
(String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
toString(), name));
}
}
}
代码示例来源:origin: apache/pulsar
@SuppressWarnings("deprecation")
public void sleepServer(final int seconds, final CountDownLatch l) throws InterruptedException, IOException {
Thread[] allthreads = new Thread[Thread.activeCount()];
Thread.enumerate(allthreads);
for (final Thread t : allthreads) {
if (t.getName().contains("SyncThread:0")) {
Thread sleeper = new Thread() {
public void run() {
try {
t.suspend();
l.countDown();
Thread.sleep(seconds * 1000);
t.resume();
} catch (Exception e) {
LOG.error("Error suspending thread", e);
}
}
};
sleeper.start();
return;
}
}
throw new IOException("ZooKeeper thread not found");
}
代码示例来源:origin: orbit/orbit
Thread.enumerate(tarray);
代码示例来源:origin: apache/kafka
@Test
public void testHeartbeatThreadClose() throws Exception {
ConsumerCoordinator coordinator = prepareCoordinatorForCloseTest(true, true, true);
coordinator.ensureActiveGroup();
time.sleep(heartbeatIntervalMs + 100);
Thread.yield(); // Give heartbeat thread a chance to attempt heartbeat
closeVerifyTimeout(coordinator, Long.MAX_VALUE, requestTimeoutMs, requestTimeoutMs);
Thread[] threads = new Thread[Thread.activeCount()];
int threadCount = Thread.enumerate(threads);
for (int i = 0; i < threadCount; i++)
assertFalse("Heartbeat thread active after close", threads[i].getName().contains(groupId));
}
代码示例来源:origin: jankotek/mapdb
/**
* Finds missing PoolCleaners
*/
void checkForkJoinPoolThreadLeaks() throws InterruptedException {
Thread[] survivors = new Thread[7];
int count = Thread.enumerate(survivors);
for (int i = 0; i < count; i++) {
Thread thread = survivors[i];
String name = thread.getName();
if (name.startsWith("ForkJoinPool-")) {
// give thread some time to terminate
thread.join(LONG_DELAY_MS);
if (thread.isAlive())
tearDownFail("Found leaked ForkJoinPool thread thread=%s",
thread);
}
}
if (!ForkJoinPool.commonPool()
.awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
tearDownFail("ForkJoin common pool thread stuck");
}
代码示例来源:origin: reactor/reactor-core
@Test
public void testCustomRequestTaskThreadName() {
String expectedName = "topicProcessorRequestTaskCreate";
//NOTE: the below single executor should not be used usually as requestTask assumes it immediately gets executed
ExecutorService customTaskExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, expectedName));
TopicProcessor<Object> processor = TopicProcessor.builder()
.executor(Executors.newCachedThreadPool())
.requestTaskExecutor(customTaskExecutor)
.bufferSize(8)
.waitStrategy(WaitStrategy.liteBlocking())
.autoCancel(true)
.build();
processor.requestTask(Operators.cancelledSubscription());
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
//cleanup to avoid visibility in other tests
customTaskExecutor.shutdownNow();
processor.forceShutdown();
Condition<Thread> customRequestTaskThread = new Condition<>(
thread -> thread != null && expectedName.equals(thread.getName()),
"a thread named \"%s\"", expectedName);
Assertions.assertThat(threads)
.haveExactly(1, customRequestTaskThread);
}
代码示例来源:origin: reactor/reactor-core
@Test
public void testDefaultRequestTaskThreadName() {
String mainName = "topicProcessorRequestTask";
String expectedName = mainName + "[request-task]";
TopicProcessor<Object> processor = TopicProcessor.builder().name(mainName).bufferSize(8).build();
processor.requestTask(Operators.cancelledSubscription());
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
//cleanup to avoid visibility in other tests
processor.forceShutdown();
Condition<Thread> defaultRequestTaskThread = new Condition<>(
thread -> thread != null && expectedName.equals(thread.getName()),
"a thread named \"%s\"", expectedName);
Assertions.assertThat(threads)
.haveExactly(1, defaultRequestTaskThread);
}
代码示例来源:origin: reactor/reactor-core
@Test
public void testDefaultRequestTaskThreadName() {
String mainName = "workQueueProcessorRequestTask";
String expectedName = mainName + "[request-task]";
WorkQueueProcessor<Object> processor = WorkQueueProcessor.builder().name(mainName).bufferSize(8).build();
processor.requestTask(Operators.cancelledSubscription());
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
//cleanup to avoid visibility in other tests
processor.forceShutdown();
Condition<Thread> defaultRequestTaskThread = new Condition<>(
thread -> thread != null && expectedName.equals(thread.getName()),
"a thread named \"%s\"", expectedName);
Assertions.assertThat(threads)
.haveExactly(1, defaultRequestTaskThread);
}
代码示例来源:origin: reactor/reactor-core
@Test
public void testCustomRequestTaskThreadShare() {
String expectedName = "topicProcessorRequestTaskShare";
//NOTE: the below single executor should not be used usually as requestTask assumes it immediately gets executed
ExecutorService customTaskExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, expectedName));
TopicProcessor<Object> processor = TopicProcessor.builder().share(true)
.executor(Executors.newCachedThreadPool())
.requestTaskExecutor(customTaskExecutor)
.bufferSize(8)
.waitStrategy(WaitStrategy.liteBlocking())
.autoCancel(true)
.build();
processor.requestTask(Operators.cancelledSubscription());
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
//cleanup to avoid visibility in other tests
customTaskExecutor.shutdownNow();
processor.forceShutdown();
Condition<Thread> customRequestTaskThread = new Condition<>(
thread -> thread != null && expectedName.equals(thread.getName()),
"a thread named \"%s\"", expectedName);
Assertions.assertThat(threads)
.haveExactly(1, customRequestTaskThread);
}
代码示例来源:origin: reactor/reactor-core
@Test
public void testCustomRequestTaskThreadNameCreate() {
String expectedName = "workQueueProcessorRequestTaskCreate";
//NOTE: the below single executor should not be used usually as requestTask assumes it immediately gets executed
ExecutorService customTaskExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, expectedName));
WorkQueueProcessor<Object> processor = WorkQueueProcessor.builder()
.executor(Executors.newCachedThreadPool())
.requestTaskExecutor(customTaskExecutor)
.bufferSize(8)
.waitStrategy(WaitStrategy.liteBlocking())
.autoCancel(true)
.build();
processor.requestTask(Operators.cancelledSubscription());
processor.subscribe();
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
//cleanup to avoid visibility in other tests
customTaskExecutor.shutdownNow();
processor.forceShutdown();
Condition<Thread> customRequestTaskThread = new Condition<>(
thread -> thread != null && expectedName.equals(thread.getName()),
"a thread named \"%s\"", expectedName);
Assertions.assertThat(threads)
.haveExactly(1, customRequestTaskThread);
}
代码示例来源:origin: reactor/reactor-core
@Test
public void testCustomRequestTaskThreadNameShare() {
String expectedName = "workQueueProcessorRequestTaskShare";
//NOTE: the below single executor should not be used usually as requestTask assumes it immediately gets executed
ExecutorService customTaskExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, expectedName));
WorkQueueProcessor<Object> processor = WorkQueueProcessor.builder()
.executor(Executors.newCachedThreadPool())
.requestTaskExecutor(customTaskExecutor)
.bufferSize(8)
.waitStrategy(WaitStrategy.liteBlocking())
.autoCancel(true)
.build();
processor.requestTask(Operators.cancelledSubscription());
processor.subscribe();
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
//cleanup to avoid visibility in other tests
customTaskExecutor.shutdownNow();
processor.forceShutdown();
Condition<Thread> customRequestTaskThread = new Condition<>(
thread -> thread != null && expectedName.equals(thread.getName()),
"a thread named \"%s\"", expectedName);
Assertions.assertThat(threads)
.haveExactly(1, customRequestTaskThread);
}
代码示例来源:origin: SeanDragon/protools
/**
* 系统线程列表
*
* @return
*/
public static List<Thread> getJvmThreads() {
int activeCount = Thread.activeCount();
Thread[] threads = new Thread[activeCount];
Thread.enumerate(threads);
return Arrays.asList(threads);
}
代码示例来源:origin: rhuss/jolokia
private Thread[] enumerateThreads() {
boolean fits = false;
int inc = 50;
Thread[] threads = null;
int nrThreads = 0;
while (!fits) {
try {
threads = new Thread[Thread.activeCount()+inc];
nrThreads = Thread.enumerate(threads);
fits = true;
} catch (ArrayIndexOutOfBoundsException exp) {
inc += 50;
}
}
// Trim array
Thread ret[] = new Thread[nrThreads];
System.arraycopy(threads,0,ret,0,nrThreads);
return ret;
}
代码示例来源:origin: sixt/ja-micro
private void brutallyKillConsumer(String victimName) {
int nbThreads = Thread.activeCount();
Thread[] threads = new Thread[nbThreads];
Thread.enumerate(threads);
for (Thread t : threads) {
if (t.getName().equals(victimName)) {
logger.error("BOOM: Killing consumer thread {}", victimName);
//noinspection deprecation
t.stop(); // used by intention despite deprecation
}
}
}
代码示例来源:origin: org.apache.commons/commons-pool2
@Test
public void testPool() throws Exception {
final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setTestWhileIdle(true /* testWhileIdle */);
final PooledFooFactory pooledFooFactory = new PooledFooFactory();
try (GenericObjectPool<Foo> pool = new GenericObjectPool<>(pooledFooFactory, poolConfig)) {
pool.setTimeBetweenEvictionRunsMillis(EVICTION_PERIOD_IN_MILLIS);
pool.addObject();
try {
Thread.sleep(EVICTION_PERIOD_IN_MILLIS);
} catch (final InterruptedException e) {
Thread.interrupted();
}
}
final Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
for (final Thread thread : threads) {
if (thread == null) {
continue;
}
final String name = thread.getName();
assertFalse(name, name.contains(COMMONS_POOL_EVICTIONS_TIMER_THREAD_NAME));
}
}
}
代码示例来源:origin: org.apache.ignite/ignite-core
/**
* @param threadId Thread ID.
* @return Thread name if found.
*/
public static String threadName(long threadId) {
Thread[] threads = new Thread[Thread.activeCount()];
int cnt = Thread.enumerate(threads);
for (int i = 0; i < cnt; i++)
if (threads[i].getId() == threadId)
return threads[i].getName();
return "<failed to find active thread " + threadId + '>';
}
代码示例来源:origin: com.google.code.maven-play-plugin.org.playframework/play
static void resetClassloaders() {
Thread[] executorThreads = new Thread[executor.getPoolSize()];
Thread.enumerate(executorThreads);
for (Thread thread : executorThreads) {
if (thread != null && thread.getContextClassLoader() instanceof ApplicationClassloader)
thread.setContextClassLoader(ClassLoader.getSystemClassLoader());
}
}
内容来源于网络,如有侵权,请联系作者删除!