I’m trying to use ExecutorService with BlockingQueue<Runnable> but I have problems in exiting the script. It finishes without problems, but then keep waiting I don’t know what.
First of all I have a class
public class GenericTask implements Runnable {
public void run() {
// do stuff
}
}
then this is the 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 “Finished!”, it is really completed, but the script continues going on unless I add a System.exit(0), but I think this is not correct.
In the end you are correctly shutting down all threads in thread pool. But there is yet another non-daemon thread that stops JVM from terminating. Can you spot it? It’s your anonymous producer thread with infinite loop inside:
for (;;).Use
Thread.setDaemon(true):Now when all threads in
ExecutorServiceterminate after shutdown,mainthread terminates as well and JVM will stop because your only remaining thread is a daemon.