'Why do threads through a loop give an error when with Executor
The sample code is taken from the Java Philosophy 2015 book and it used Java SE5/6. I used JDK11, maybe this code is not suitable for the new version, but why?
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i=0;i<5;i++) {
exec.execute(new LiftOff2());
exec.shutdown();
}
}
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task LiftOff2@5f205aa rejected from java.util.concurrent.ThreadPoolExecutor@6d86b085[Shutting down, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]
at java.base/java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2055)
at java.base/java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:825)
at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1355)
at Runnable_p897.main(Runnable_p897.java:8)
Solution 1:[1]
From the documentation of ExecutorService::shutdown:
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. ...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Turing85 |
