alibaba / alibaba/p3c

关于线程池Executors 提供的newScheduledThreadPool

Open
#808 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Kotlin
Stars
30.9k
Forks
8k
PR merge metrics
No merged PRs in 30d

Description

## 规约原文
【强制】线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这
样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
说明:Executors 返回的线程池对象的弊端如下:
1) FixedThreadPool 和 SingleThreadPool:
允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM。
2) CachedThreadPool:
允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。

## 问题描述
Executors提供的newScheduledThreadPool存在如下问题:
newScheduledThreadPool最终默认使用的参数为maximumPoolSize=Integer.MAX_VALUE, workQueue=DelayedWorkQueue。
但是DelayedWorkQueue是一个无界队列,会导致maximumPoolSize这个参数失效,高并发情况下,任务会堆积在队列中,导致oom。
测试代码:
ScheduledExecutorService service = Executors.newScheduledThreadPool(15);
new Thread(() -> {
while (true) {
service.execute(() -> {
while (true) {
}
});
}
}).start();

try {
TimeUnit.SECONDS.sleep(25);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("done");

## 修改建议
newScheduledThreadPool可能会堆积大量的请求,从而导致 OOM。

Contributor guide

No contributing guide indexed for this repository

Research direction

No source file or test is named. Start by locating the rule or inspection that handles Executors.newScheduledThreadPool, then reproduce the unbounded DelayedWorkQueue behavior from the issue; done should include an agreed rule or guidance change and coverage for this case.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.