We all know that when catching an interruptedexception we are supposed to Thread.currentThread().interrupt();
However, from my tests, that flag is already set.
Thread t = new Thread(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// Thread.currentThread().interrupt();
}
});
t.start();
System.out.println(t.isInterrupted());
t.interrupt();
System.out.println(t.isInterrupted());
Prints:
false
true
So what is the point of that commented out line?
If the line is commented out and you try to check in the thread itself if it is interrupted, you will get false as response.
If you execute the line you get true.
Edit: The use of
interrupt()is to inform the thread that it should be terminated. It replaces thestop()method which immediately terminates a thread at the currently executed line. Since stopping leaves files or streams open, this way is deprecated. The interrupt should be used to safely close all open streams and then safely terminate the thread. If the thread does not have the ability to create ghosts (leave streams/files open), the handling can be omitted. However, it should always be remembered that theinterrupt()method does not terminate the thread, instead it continues to execute the code after the exception as if nothing had happened.