Maximum number of threads in a JVM?

后端 未结 6 614

What are the maximum number of threads which can be maintained by the Java virtual machine?

I did not explain this in my original question, but I am trying to benchm

6条回答
  •  眼角桃花
    2020-12-01 11:24

    Maximum thread limit mainly depends on hardware, OS and Java stack size.

    The following factor plays a very important role to identify max thread limit:-

    1. Process virtual address limit (2^32 for 32-bit architecture and 2^64 for 64-bit architecture)
    2. Java stack size (can be determine by command java -XX:+PrintFlagsFinal -version | grep -iE 'ThreadStackSize'
    3. Max PID limit (can be determine by command "cat /proc/sys/kernel/pid_max")
    4. Max process limit ulimit -u

    So max thread limit will be MINIMUM of ((process virtual address space/java stack size), Max PID limit, Max process limit)

    e.g. if Max process limit is 2048 and it is minimum of all above mention three-factor then java process will not be able to create a thread more than that.

    To verify it one can create simple java application in which he/she can create a thread in a loop and see how much it can go.

    Example:

    public class ThreadCountTest {
      private static final Object lock = new Object();
      private static int counter = 0;
        
      public static void main(String[] _args) {
        while (true) {
          new Thread(new Runnable() {
            public void run() {
              synchronized(lock) {
                counter++;
                System.err.println("New thread #" + counter);
              }
              while (true) {
                try {
                  Thread.sleep(3000);
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            }
          }).start();
        }
      }
    }
    

提交回复
热议问题