-1

While reading through someone else's code, I came across the following:

class Worker extends Thread {

....

         public void run() {
            try {
                while ( true ) {
                    ..... DO WORK .....
                }
            } catch ( InterruptedException e ) {
                Thread.currentThread().interrupt();
            } catch ( RuntimeException e ) {
                handleFatal( e );
            }
        }
}

What is the effect of calling Thread.currentThread().interrupt() inside the catch block?

Surely the current running thread - this instance of Worker - is already interrupted at this point? What purpose does it serve to call interrupt() again on an already interrupted thread?

Mikepote
  • 6,042
  • 3
  • 34
  • 38

1 Answers1

0

An InterruptedException doesn't mean that the thread is in the interrupted state. It means that the thread entered the interrupted state, then a polling method (like Object.wait or Thread.sleep) checked if the thread was in the interrupted state (doing so brings the thread out of the interrupted state) and throws the exception. So when the exception is caught, the thread is no longer in the interrupted state.

It seems that the purpose of that catch block is to intercept such exceptions and put the thread back in the interrupted state.

Leo Aso
  • 11,898
  • 3
  • 25
  • 46