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())?
Yes, you should be introduce a volatile boolean to control the loop. Not just because of the possibility of a spurious interrupt, but because it makes the code more readable.
You're not achieving a clever optimization by "saving" a boolean and using the interrupt status of the thread to control the loop, you're making it less obvious as to what the working mechanism of the class is.
Edit: I wasn't really answering the core question (mixed it up with wakeups). As we know, spurious wakeups can and do happen, which is why we use guard clauses/loops to check that a condition has really been satisfied.
Spurious interrupts aren't a thing, meaning there's always one thread interrupting another inside the Java ecosystem (unlike with wakeups, where the reason is external). Interrupting random threads is not something that the Java platform does by itself, but you could write a thread that just randomly selects other threads and tries to interrupt them. However that wouldn't be a spurious interrupt, that would be a malicious interrupt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With