Why invoke Thread.currentThread.interrupt() in a catch InterruptException block?

Hesey picture Hesey · Feb 5, 2011 · Viewed 53.4k times · Source

Why invoke the method Thread.currentThread.interrupt() in the catch block?

Answer

Péter Török picture Péter Török · Feb 5, 2011

This is done to keep state.

When you catch the InterruptException and swallow it, you essentially prevent any higher level methods/thread groups from noticing the interrupt. Which may cause problems.

By calling Thread.currentThread().interrupt(), you set the interrupt flag of the thread, so higher level interrupt handlers will notice it and can handle it appropriately.

Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3: Responding to Interruption. Its rule is:

Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.