In service code, I have a ScheduledTaskExecutor that starts a job, then a second thread that will cancel that first thread by interrupting it. The job checks for interrupts intermittently, and when the job gets one, it will throw an InterruptException; the service has a try/catch around that job and the catch handles that interruption. My problem is, the catch block is never hit. The job is definitely being interrupted, clear from logging statements on the job side, Once it throws the InterruptException, it's lost and the service can't catch it.
I tried changing Thread.interrupted() to Thread.currentThread().interrupted(), but it didn't fix the problem.
Here's the server-side code that waits for the InterruptException from the job. The interrupt signal is sent to thread via another thread that's scheduled to run after a timeout. I've verified the job does get the interrupt signal.
private void run() {
try {
job.run();
} catch (InterruptedException e) {
log.info("Job was interrupted", e);
} finally {
duration.stop();
timer.record(duration);
}
}
Here's how the job checks for interrupts:
public void checkForInterrupt() throws InterruptedException {
if (Thread.currentThread().isInterrupted()) {
logger.info(jobName + " was interrupted");
throw new InterruptedException(jobName + " has been interrupted");
}
}
I'm expecting to see this log line log.info("Job was interrupted", e);
The last thing I hear from the thread is a log statement that confirms it's interrupt flag has been set, after which it throws the InterruptedException.