google / google/error-prone

New rule: Buggy ThreadPoolExecutor initializations

Open
#1,510 1 comment 1 reaction 0 assignees View on GitHub
Type-NewCheck
Dominant language
Java
Stars
7.2k
Forks
820
Avg merge
5h 9m
Merged PRs (30d)
50

Description

### Description of the feature request:

Imagine this:
```java
executor = new ThreadPoolExecutor(
1, 4,
1, TimeUnit.MINUTES,
new LinkedBlockingQueue<>()
);
```

This appears to try to create a TPE with a single thread that scales up to four threads when tasks come in. So what will happen if this executor gets 5 requests at the same time?

Only a single thread will be created, four tasks will wait in a queue. In fact, this executor will never have more than 1 thread.

See [`ThreadPoolExecutor`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ThreadPoolExecutor.html), section "Queueing".

The insight here is that after the core threads are running, the executor prefers to enqueue tasks instead of starting extra threads. For an unbounded queue, that means that only core threads will ever run.

A bounded queue with a limit high enough (Millions? Maybe. Definitely `Integer.MAX_VALUE`, though.) will effectively behave the same.

The rule should suggest to either use `coreThreads == maxThreads` (optionally with `executor.allowCoreThreadTimeOut(true)`), or use an effectively bounded queue (or simply suggest the `Executors` class).

### Feature requests: what underlying problem are you trying to solve with this feature?

An actual bug pattern that occasionally pops up, is hard to find and debug.

### What version of Error Prone are you using?

2.3.4

### Have you found anything relevant by searching the web?

This is known behaviour of TPE that was discussed a few times at the concurrency-interest mailing list. The behaviour makes sense, but is initially unintuitive and error-prone.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.