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.
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.
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.
As stated in the documentation, you cannot reuse an ExecutorService that has been shut down.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With