I am creating a task poller which looks for tasks every minute. It looks like this:
public class Poller {
private final ExecutorService e = Executors.newSingleThreadExecutor();
public void start() {
e.submit(() -> {
while (!Thread.currentThread().isInterrupted()) {
final Task task = manager.getTask();
if (task != null) {
// ...
} else {
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
});
}
public void stop() {
e.shutdownNow();
}
}
When I want to stop the poller process, I exucute stop()
. This triggers an interrupt on the running thread, which will stop the poller.
This works fine. However, I am wondering if there is a possibility that this thread will be interrupted by someone else, most likely the JVM. In that case, the poller will quit while it shouldn't.
I know we can have spurious wakeups, so we have to guard a wait()
with a while (condition) { ... }
instead of if (condition) { ... }
. Can it also occur that the JVM will interrupt an ongoing thread for no good reason?
In that case, I should introduce a volatile boolean
and check on that instead of while (!Thread.currentThread().isInterrupted())
?