General Esdeath
General Esdeath

Reputation: 21

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)

Upvotes: 1

Views: 538

Answers (1)

Turing85
Turing85

Reputation: 20195

From the documentation of ExecutorService::shutdown:

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. ...

Upvotes: 1

Related Questions