ThreadPoolExecutor创建线程池启动项目报错问题

ThreadPoolExecutor创建线程,如下代码:
ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1, 20, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), new ThreadPoolExecutor.CallerRunsPolicy());

启动项目时,报错如下:
Constructor threw exception; nested exception is java.lang.IllegalArgumentException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 37 common frames omitted
Caused by: java.lang.IllegalArgumentException: null
at java.util.concurrent.ThreadPoolExecutor.<init>(ThreadPoolExecutor.java:1314) [na:1.8.0_162]
at java.util.concurrent.ThreadPoolExecutor.<init>(ThreadPoolExecutor.java:1272) [na:1.8.0_162]

原因分析:corePoolSize必须小于等于maximumPoolSize,而Runtime.getRuntime().availableProcessors() + 1有可能大于20,这时就会抛出IllegalArgumentException,这可以在源码中看到,如下图:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}

解决。只需要保证corePoolSize总是<=maximumPoolSize即可,如:
ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1, Runtime.getRuntime().availableProcessors()*2, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), new ThreadPoolExecutor.CallerRunsPolicy());
————————————————
版权声明:本文为CSDN博主「打不死的小强lee」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wenqiangluyao/article/details/125768360

posted @ 2022-12-17 18:02  疯子110  阅读(569)  评论(0编辑  收藏  举报