Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to shutdown ExecutorService fixedThreadPool

I have created threadpool using ExecutorService, in my application to call vendor websrvice, using below code.

  ExecutorService executor = Executors.newFixedThreadPool(getThreadPoolSize());
    for (int i = 0; i < list.size(); i++) {
                    Request ecpReq = list.get(i);           
                    thRespLst.add(executor.submit(new Task(ecpReq)));
                }

Wanted to know do we need to take care of shutting down threadpool or something, basically I don't want hanging threads in production environment.

like image 263
Prateek Shrivastava Avatar asked Jul 29 '15 14:07

Prateek Shrivastava


People also ask

Does ExecutorService shutdown automatically?

Using shutdown() and awaitTermination​() In general, the ExecutorService will not be automatically destroyed when there is no task to process. It will stay alive and wait for new tasks to come.

What does ExecutorService shutdown do?

Shutting down the ExecutorService shutdown() - when shutdown() method is called on an executor service, it stops accepting new tasks, waits for previously submitted tasks to execute, and then terminates the executor.

Can I use ExecutorService after shutdown?

As stated in the documentation, you cannot reuse an ExecutorService that has been shut down.

How do I shut down ExecutorService gracefully?

When using an Executor, we can shut it down by calling the shutdown() or shutdownNow() methods. Although, it won't wait until all threads stop executing. Waiting for existing threads to complete their execution can be achieved by using the awaitTermination() method.


1 Answers

  • newFixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads)

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.

Javadocs.

Here a good explanation.

like image 92
Fabio Cardoso Avatar answered Sep 29 '22 18:09

Fabio Cardoso