congrats Icon
New! Announcing Tabnine Chat Beta
Learn More
Tabnine Logo
Thread.enumerate
Code IndexAdd Tabnine to your IDE (free)

How to use
enumerate
method
in
java.lang.Thread

Best Java code snippets using java.lang.Thread.enumerate (Showing top 20 results out of 423)

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());
  }
}
java.langThreadenumerate

Javadoc

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.

Popular methods of Thread

  • currentThread
  • sleep
    Causes the currently executing thread to sleep (temporarily cease execution) for the specified numbe
  • <init>
    Constructs a new Thread with no Runnable object, the given name and belonging to the ThreadGroup pas
  • start
    Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread
  • getContextClassLoader
    Returns the context ClassLoader for this Thread. The context ClassLoader is provided by the creator
  • interrupt
    Interrupts this thread. Unless the current thread is interrupting itself, which is always permitted,
  • setDaemon
    Marks this thread as either a #isDaemon thread or a user thread. The Java Virtual Machine exits when
  • getName
    Returns this thread's name.
  • join
    Waits at most millis milliseconds plus nanos nanoseconds for this thread to die. This implementatio
  • setContextClassLoader
    Sets the context ClassLoader for this Thread. The context ClassLoader can be set when a thread is cr
  • setName
    Changes the name of this thread to be equal to the argumentname. First the checkAccess method of thi
  • interrupted
    Tests whether the current thread has been interrupted. Theinterrupted status of the thread is cleare
  • setName,
  • interrupted,
  • getStackTrace,
  • getId,
  • isInterrupted,
  • isAlive,
  • setPriority,
  • yield,
  • getThreadGroup,
  • getPriority

Popular in Java

  • Making http post requests using okhttp
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • runOnUiThread (Activity)
  • getResourceAsStream (ClassLoader)
  • Rectangle (java.awt)
    A Rectangle specifies an area in a coordinate space that is enclosed by the Rectangle object's top-
  • SocketException (java.net)
    This SocketException may be thrown during socket creation or setting options, and is the superclass
  • BlockingQueue (java.util.concurrent)
    A java.util.Queue that additionally supports operations that wait for the queue to become non-empty
  • JComboBox (javax.swing)
  • Scheduler (org.quartz)
    This is the main interface of a Quartz Scheduler. A Scheduler maintains a registry of org.quartz.Job
  • SAXParseException (org.xml.sax)
    Encapsulate an XML parse error or warning.> This module, both source code and documentation, is in t
  • CodeWhisperer alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now