Klaus
Klaus

Reputation: 1731

Is shutting down a thread pool mandatory?

I have a web method that calls a method performs a computational task. I have used a multi-threaded approach to call this method using java ExecutorService. Here is my code so far:

@WebMethod
public void performIntensiveCalculation()
{
    ExecutorService pool = CalculationThreadPool.getInstance().getThreadPool();
    pool.execute( calculate );
}

My CalculationThreadPool implementation is as follows,

public class CalculationThreadPool
{

    private static CalculationThreadPool instance;

    private ExecutorService pool;

    private CalculationThreadPool()
    {
        pool = Executors.newFixedThreadPool( 3 );
    }

    public synchronized static CalculationThreadPool getInstance()
    {
        if( instance == null )
        {
            instance = new CalculationThreadPool();
        }
        return instance;
    }

    public ExecutorService getThreadPool()
    {
        return pool;
    }  

}

Since this method is exposed as a web method, requests can come at any time to perform the calculation. What I cannot understand is how to call the shutdown method in the created pool. If I call the pool.shutdown() just after the pool.execute() line, future requests will not be able to use the thread pool.

Is it a bad practice to keep the thread pool without shutting down? Am I using wrong way to get my task done? Is there any better way?

Upvotes: 1

Views: 1649

Answers (1)

Ehsan Khodarahmi
Ehsan Khodarahmi

Reputation: 4922

Connection pool should be available throughout your webapp lifetime, otherwise, using it will only cause overhead! This is why your CalculationThreadPool uses singleton pattern.
I don't think you need to shutdown the thread pool manually, since jvm will kill all threads upon shutdown. Anyway, if you still need to shut in down manually, one solution is to add a ServletContextListener and do it in its contextDestroyed method. Something like this:

@WebListener
public class MyContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent e)
    {
        CalculationThreadPool.getInstance().getThreadPool().shutdownNow();
    }
}

Be aware that there are two methods for shutting down a thread pool: shutdown and shutdownNow that are slightly different in terms of coping with currently running tasks, you can take a look at ExecutorService documentation for more details.

Upvotes: 3

Related Questions