I have recently inherited a large Java Application that has almost no Thread safety in it. What I’m currently working on is getting all of the Threads to correctly handle being interrupted instead of using the very bad Thread.stop().
Part of the problem has been that I do not know every method call out there that clears the interrupt flag.
Currently I know that the following will clear the interrupt flag:
Thread.interrupted()
Thread.sleep(long)
Thread.join()
Thread.join(long)
Object.wait()
Object.wait(long)
What else am I missing? Thank you
It is important to clarify that the following methods clear the interrupt flag by just calling them:
For this reason
Thread.currentThread().isInterrupted()should always be used instead.The following methods will clear the interrupted flag by immediately throwing
InterruptedExceptioneither if they were called and then the thread was interrupted or if the thread was already interrupted and then they were called (see junit code below). So it is not the method that clears the flag, throwing the exception does.Your initial list:
Added to your list:
Please note that the proper pattern with any code that catches
InterruptedExceptionis to immediately re-interrupt the thread. We do this in case others are relying on thethread.isInterrupted()method:JUnit code that demonstrates some of this: