The following program demonstrates the problem (latest JVM & whatnot):
public static void main(String[] args) throws InterruptedException {
// if this is true, both interrupted and isInterrupted work
final boolean withPrint = false;
// decide whether to use isInterrupted or interrupted.
// if this is true, the program never terminates.
final boolean useIsInterrupted = true;
ExecutorService executor = Executors.newSingleThreadExecutor();
final CountDownLatch latch = new CountDownLatch(1);
Callable<Void> callable = new Callable<Void>() {
@Override
public Void call() throws Exception {
Random random = new Random();
while (true) {
if (withPrint) {
System.out.println(random.nextInt());
System.out.flush();
}
if (useIsInterrupted)
{
if (Thread.currentThread().isInterrupted())
break;
}
else
{
if (Thread.interrupted())
break;
}
}
System.out.println("Nice shutdown");
latch.countDown();
return null;
}
};
System.out.println("Task submitted");
Future<Void> task = executor.submit(callable);
Thread.sleep(100);
task.cancel(true);
latch.await();
System.out.println("Main exited");
executor.shutdown();
}