Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

Javadoc says: "An unused ExecutorService should be shut down to allow reclamation of its resources." – Marvin Jul 29, 2015 at 15:09 Your iterating is not thread-safe: calling list.size() may return a number N and right after that, before you call list.get(i) the Nth element may have been deleted. – V G Jul 29, 2015 at 15:37

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.

FinalizableDelegatedExecutorService and ThreadPoolExecutor override finalize() to do the shutdown.

* Invokes {@code shutdown} when this executor is no longer * referenced and it has no threads. protected void finalize() { shutdown();

Acutally, I see no reason to explicitly shutdown the ExecutorService.

ExecutorService must be shutdown explicitly to reclaim the resources (CPU & Memory) occupied by threads which have already finished their job but still exist. – Ashish Kumar Nov 30, 2017 at 10:31

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.