Amri Maher
Amri Maher

Reputation: 58

threads created by ThreadPoolExecutor keeps running after shutdown

I am trying to apply the priciple of Multithread producer/consumer of some datas using two threadPoolExecutors, i noticed that everything works fine but the program refuse to shut down and some threads are still running after shutting down the 2 threadPools:

In main class:

ExecutorService executor = new ThreadPoolExecutor(10, 10, 40, TimeUnit.SECONDS,
        new ArrayBlockingQueue<Runnable>(edmsIds.size()));
ExecutorService consumerExecutor =  new ThreadPoolExecutor(10, 10, 0L, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(edmsIds.size()));for(
String edmsID:edmsIds)

{

    Runnable worker = new BatchWorkerThread(resumeFile, stratrKeysToUpdate, xslFiles, errorThrown, edmsID,
            consumerExecutor, edmsIds.size(), executor);
    executor.execute(worker);
}

In producer Class:

while (edmsNumber > 0) {
    Runnable consumer = new ConsumerThread(brokerWorker);
    consumExecutor.execute(consumer);//decreasing the edmsNumber

}
if (edmsNumber < 1) {
    prodExecutor.shutdownNow();
    consumExecutor.shutdownNow();
}

Upvotes: 0

Views: 1357

Answers (2)

Amri Maher
Amri Maher

Reputation: 58

Actually i wanted to post the cause of the problem and the solution :


  • Cause

    i was trying to shutdown the excutor while it is not terminated yet.

  • Solution

    shut it down only after its termination using a simple code.

For example :

prodExecutor.shutdownNow(); while (!prodExecutor.isTerminated()) {}

  • Another solution is to use ExecutorCompletionService if you want to take tasks as they complete you need an ExecutorCompletionService. This acts as a BlockingQueue that will allow you to poll for tasks as and when they finish.

Upvotes: 1

xingbin
xingbin

Reputation: 28269

See the doc:

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

If the running task is not interruptable(does not respond to interrupt singal), it will continue execute.

Upvotes: 4

Related Questions