Understand when ExecutorService ends

I am trying to use ExecutorService with BlockingQueue<Runnable> , but I am having problems exiting the script. It ends without problems, but then continue to wait, I do not know what.

First of all, I have a class

 public class GenericTask implements Runnable { public void run() { // do stuff } } 

then this is code

 BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(10000, true); ExecutorService myExecutor = Executors.newFixedThreadPool(numThreads); new Thread(new Runnable() { public void run() { for (; ; ) { try { myExecutor.execute(queue.take()); } catch (InterruptedException ignored) { } } } }).start(); while (...) { queue.put(new GenericTask()); } int waitTime = 500; myExecutor.shutdown(); try { while (!myExecutor.awaitTermination(waitTime, TimeUnit.MILLISECONDS)) { logger.info("Waiting..."); Thread.sleep(waitTime); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Finished!"); 

When it prints β€œDone!”, It is really complete, but the script continues if I do not add System.exit(0) , but I think this is not true.

+4
source share
1 answer

In the end, you correctly close all threads in the thread pool. But there is another non-daemon thread that stops the JVM from terminating. Can you spot it? This is an anonymous producer stream with an infinite loop inside: for (;;) .

Use Thread.setDaemon(true) :

 Thread t = new Thread(new Runnable() { //... }); t.setDaemon(true); t.start(); 

Now that all the threads in the ExecutorService finished after the shutdown, the main thread ends and the JVM stops because your only remaining thread is the daemon.

+4
source

All Articles