I was task with implementing a background thread to do backend async processing with the twist being were certain cases where the job needed to be externally stopped.
I implemented it by wrapping everything within the Runnable in a try catch block and catch the InterruptionException, if caught the thread will simply return and exit.
Runnable task = () -> {
try {
while (true) {
// do stuff
// sleep for interval
Thread.sleep(this.checkInterval);
}
} catch (InterruptedException ex) {
// cleanup and exit
return; // exit thread
} catch (Exception ex) {
// cleanup and exit
return; // exit thread
}
};
I'm using the ExecutorService SingleThreadExecutor and submitting the job like the following.
this.job = executorService.submit(task);
Then I am stopping the thread using
boolean canceled = this.job.cancel(true);
It seems to work fine since the cancel causes an InterruptionException if the thread is running.
Is this code safe, meaning when cancel is called its always guaranteed to kill the thread?