Search code examples
javamultithreadingcachingwaitexecutor

Threads in Cached Thread Pool never being removed


So, I have a server like this:

public class Server {
    private ExecutorService executor = null;

    private class WorkerThread implements Runnable{ 


        public void run() {
            try{
                do{
                    synchronized(executor){
                        executor.wait();
                    }
                    // doSomeThing
                }while(true);
            } catch (InterruptedException e) {
            }
        }
    }

    Server() {
        executor = Executors.newCachedThreadPool();
    }

    public void calledWhenTriggerEventOccurs(){
        synchronized(executor) {
            executor.execute(new WorkerThread());
            executor.notify();}
    }
}

After calledWhenTriggerEventOccurs() is called for 3 times in a row, 3 new threads are being placed in the executors pool. Then I just wait for 90 sec.

I now would expect the previous 3 threads to be dead. But they are still alive. When I call calledWhenTriggerEventOccurs() once again a 4th thread is being created.

So why are those 3 threads not being removed as I would expect?


Solution

  • Your tasks most likely wait forever so I wouldn't expect them to die, no matter how long you wait. When you notify() and there isn't any threads waiting the notify is lost. Most likely you have notified three times before your three tasks have a chance to start.