/** * @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 + '>'; }
/** 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(); } }
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; } }
/** * 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)); } } }
@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"); }
Thread.enumerate(tarray);
@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)); }
/** * 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"); }
@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); }
@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); }
@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); }
@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); }
@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); }
@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); }
/** * 系统线程列表 * * @return */ public static List<Thread> getJvmThreads() { int activeCount = Thread.activeCount(); Thread[] threads = new Thread[activeCount]; Thread.enumerate(threads); return Arrays.asList(threads); }
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; }
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 } } }
@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)); } } }
/** * @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 + '>'; }
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()); } }