Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8365974

Thread startup is slow when a large number of threads exit

XMLWordPrintable

      Thread startup is slow when a large number of threads exit.Sometimes thread startup takes more than 30 seconds on my machine.


      ```
      public class ThreadStartTest {
          private static Thread[] threads = new Thread[30000];
          private static volatile boolean done = false;

          public static void main(String[] args) {
              test();
          }

          private static void test() {
              Thread thread = new Thread(new Runnable() {
                  @Override
                  public void run() {
                      while (true) {
                          for (int i = 0; i < threads.length; i++) {
                              Thread myThread = new Thread(new MyThread());
                              myThread.setDaemon(true);
                              threads[i] = myThread;
                          }

                          for (int i = 0; i < threads.length; i++) {
                              long start = System.nanoTime();
                              threads[i].start();
                              long end = System.nanoTime();
                              long time = end - start;
                              if (time > 10_000_000) {
                                  System.out.println(threads[i].getName() + " took " + time + " nanoseconds");
                              }
                          }
                          done = true;
                          try {
                              Thread.sleep(100L);
                          } catch (InterruptedException e) {
                              throw new RuntimeException(e);
                          }
                          done = false;
                      }
                  }
              });
              thread.setName("Producer Thread");
              thread.start();
          }

          private static class MyThread implements Runnable {
              @Override
              public void run() {
                  while (!done) {
                      try {
                          Thread.sleep(100L);
                      } catch (InterruptedException e) {
                          throw new RuntimeException(e);
                      }
                  }
              }
          }
      }

      ```

            Unassigned Unassigned
            zxie Zhaokun Xie
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: