Pergunta

I am hoping almost everyone who has used ExecutorService to running Threads must have observed this. But I could not find any solutions to this problem. And hence I am asking.

My below program never comes to a Halt. I have waited for 5 minutes now, but the program is still running.

When I add executor.shutdown(), the program stops. While I know what shutdown() method does, what I am not sure is DO WE HAVE TO CALL THIS METHOD EVERYTIME WE USE A EXECUTORSERVICE?

public class Latch implements Runnable{

    /**
     * @param args
     */
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(3);
        ExecutorService executor = Executors.newFixedThreadPool(10); 
        for(int i = 0; i < 3; i ++){
        executor.execute(new Latch(latch)); 
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("STOPPED");
        executor.shutdown();
    }

    CountDownLatch latch;

    Latch(CountDownLatch latch){
        this.latch = latch;
    }

    @Override
    public void run(){
        System.out.println("Thread Started");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        latch.countDown();

    }

}
Foi útil?

Solução

The javadoc of Executors.newFixedThreadPool() states

The threads in the pool will exist until it is explicitly shutdown.

Basically that ExecutorService spawns some non-daemon threads that it doesn't stop until you call shutdown(). Your process will not end until all non-daemon threads die.

So call it if you need your application to end or use your own ThreadFactory. Here is an improved version using daemon threads and a thread pool with as many threads as your computer has CPU cores:

Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory()
{
    @Override
    public Thread newThread(final Runnable r) {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t;
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top