Maximum number of threads in a JVM?

后端 未结 6 612

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:40

    The real question should be not how many threads you can create but how many threads will run efficiently. Too many threads and you will cause thrashing, too few and less computation time.

    First, question, how long to live is your thread. Short live threads are hardly worth the effort. Large computations on the other hand make perfect sense.

    Second, how much memory will each thread consume. Take the amount of memory each thread requires and divided it by the amount of memory available. You should not create more threads than this.

    Thirdly, how many CPUs do you have available. You should not create more threads than CPUs. In fact, you should consider at least one less than the number of threads. On a windows laptop with 4 CPUs, you should never have more than 3 Threads if efficient processing is required.

    Finally, what does your thread do. If it reads and writes to a hard drive, then you can have more threads than the number of CPUs since it will have to wait for the device to respond. Consider the following method when deciding the number of threads:

    public static int recommendedThreadCount()
    {
        int mRtnValue = 0;
        Runtime runtime = Runtime.getRuntime();
        long maxMemory = runtime.maxMemory();
        long mTotalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        int mAvailableProcessors = runtime.availableProcessors();
    
        long mTotalFreeMemory = freeMemory + (maxMemory - mTotalMemory);
        mRtnValue = (int)(mTotalFreeMemory/4200000000l);
    
        int mNoOfThreads = mAvailableProcessors-1;
        if(mNoOfThreads < mRtnValue) mRtnValue = mNoOfThreads;
    
        return mRtnValue;
    }
    

提交回复
热议问题