I have an application that runs something repeatedly in a while loop in a separate thread until the user triggers a shut down signal. I can send the signal from main thread to the worker thread by setting a (volatile) boolean field in the worker thread, but is there any other way of shut down/interrupt a thread, e.g. by means of any utility from 'java.util.concurrent'?
I have tried calling shutdown() or shutdownNow() method of the ExecutorService, but they fail to stop the worker thread. Also calling shutdown() and using !Thread.currentThread().isInterrupted()
in the while condition as recommended here is failing to break the loop. The only other way I could find was to use a CountDownLatch, but here I would have to use CountDownLatch.getCount() != 0
in the condition for while loop, but the javadoc documentation of this method says
This method is typically used for debugging and testing purposes.
which makes it a questionable approach IMO. Below is my sample code
class Worker implements Runnable {
//private volatile boolean shutdown = false; --> alternative to countdownlatch
@Override
public void run() {
while (countDownLatch.getCount() != 0) {
//do some work
}
}
}
public class App {
public static void main(String[] args) {
System.out.println("Press enter to stop");
CountDownLatch countDownLatch = new CountDownLatch(1);
ExecutorService es = Executors.newFixedThreadPool(1);
es.execute(new Worker(countDownLatch));
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
System.out.println("Shut down signal received");
countDownLatch.countDown(); //an alternative would be to set a boolean variable in worker
es.shutdownNow();
}
}
Are there any other clean way of doing this?