如何确定最大可能的固定线程池大小? [英] How to determine the max possible fixed thread pool size?

查看:103
本文介绍了如何确定最大可能的固定线程池大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法或实用程序来确定程序中可以创建多少个线程,例如使用 Executors.newFixedThreadPool(numberThreads)?以下自定义部署有效,但显然不是企业级解决方案:

Is there a method or utility to determine how many threads can be created in a program, for example with Executors.newFixedThreadPool(numberThreads)? The following custom rollout works but is obviously not an enterprise grade solution:

public class ThreadCounter {
    public static void main(String[] args) {
        System.out.println("max number threads = " + getMaxNumberThreads());
    }

    static int getMaxNumberThreads() {
        final int[] maxNumberThreads = {0};
        try {
            while (true) {
                new Thread(() -> {
                    try {
                        maxNumberThreads[0]++;
                        Thread.sleep(Integer.MAX_VALUE);
                    } catch (InterruptedException e) {
                    }
                }).start();
            }
        } catch (Throwable t) {
        }
        return maxNumberThreads[0];
    }
}


推荐答案

所以通常,创建多于您拥有的处理器数量的线程并不是很好,因为您可能会发现上下文切换之间存在瓶颈。您可以使用可用的availableProcessors()方法找到线程数,如下所示:

So as a general rule, creating more threads than the number of processors you have isn't really good because you may find bottlenecks between context switching. You can find the number of threads using the available availableProcessors() method like so:

numThreads = Runtime.getRuntime().availableProcessors();
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numThreads);

这将提供良好的常规可伸缩性,因为所有可用处理器都将在您的线程池中使用。

This provides good general scalability as all available processors will be used in your thread pool.

现在,有时由于很多I / O阻塞或其他因素,您可能会发现增加线程数量超出现有数量可能是有意义的可用。在这种情况下,您可以乘以numThreads的结果,例如将线程池加倍:

Now sometimes, due to a lot of I/O blocking, or other factors, you may find that it may make sense to increase the number of threads beyond what you have available. In which case you can just multiply the result of numThreads for example to double the thread pool:

executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numThreads * 2);

我只建议在完成一些基准测试后再看是否值得。

I would only recommend this once some benchmarking has been done to see if it's worth it though.

因此,这并不是最大的理论限制(由基础操作系统决定),但它可能为您提供了能够利用以下优势的实际限制您的计算机的硬件。

So it's not a max theoretical limit as such (which will be determined by the underlying operating system), but it probably provides you with the realistic limit of being able to take advantage of your computer's hardware.

希望这会有所帮助!

这篇关于如何确定最大可能的固定线程池大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆