Java – calculates the maximum number of threads that can be used for better performance in ThreadPool

Recently, I was faced with an interview. The interviewer asked me what is the maximum thread you can assign to the thread pool I replied that it would depend on the hardware combination

He doesn't seem satisfied with it

Anyone can tell us how to decide which maximum threads we should use for better performance Any links to the guide (in the core Java application) will be appreciated

Solution

Anyone can tell us how to decide which maximum threads we should use for better performance - it's definitely not the maximum number of threads

For best performance, the number of threads should be equal to the number of processor cores (don't forget to use - xmsyyyym and - xmxyyyym. Without them, you may encounter a situation where the processor does not assign threads to the core)

Your answer to the maximum thread is correct, depending on the hardware and operating system On Linux, you can check:

cat /proc/sys/kernel/threads-max

Edit

You can use integer MAX_ Value create thread pool

But you limit the maximum thread usage It's in my notebook The command "cat / proc / sys / kernel / threads Max" shows me 126987

My running code:

package com.stackoverflow.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestMaxAmountOfThreads {
  public static void main(String[] args) {
    ExecutorService serivce = Executors.newFixedThreadPool(Integer.MAX_VALUE);
    for (int i = 0; i < Integer.MAX_VALUE; i++) {
      serivce.submit(new Runnable() {
        public void run() {
          try {
            Thread.sleep(Integer.MAX_VALUE);
          } catch (InterruptedException e) {
          }
        }
      });
      System.out.println(i);
    }
  }
}

Output:

So I can only use 31850 threads without JVM tuning

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>