0

What happen's to a thread if you catch an InterruptedException, but don't use the Thread.currentThread().interrupt(); command? How does the thread behaves?

David Mana
  • 111
  • 1
  • 6

2 Answers2

2

InterruptedException that you catch means that someone asked your thread to stop by calling interrupt(). You need to do two steps, of which one can be done in two different ways.

  • first, you need to make sure that whatever loop you were in is broken out of. The easiest way to do it is to catch the exception outside of the loop.

  • second, you need to ensure that the thread will stop.

    • This can be done by writing your code to actually exit the thread - an easy thing to do when you caught the exception in the run() method, for example.

    • Or you can call Thread.currentThread().interrupt() and exit whatever method you're in. This will allow any loop at the higher level in the call stack to handle the interruption, hopefully performing the 2 steps I am describing.

In either case, make sure you leave your data in consistent state, safe to be used by other threads.

Also, if you intend your thread to be interruptable, do not forget to check for Thread.currentThread().interrupted() in your loop condition. Only some methods throw InterruptedException and you may not have such methods in your loop.

0

It behaves the same way as if it had not been interrupted: you have ignored the exception asking you to stop running, and you have kept cleared the interrupt flag, that is supposed to be polled regularly to know if you should stop running.

So the code executed by the thread can't know it has been interrupted anymore, and it will thus keep running as if nothing happened, until the thread is interrupted again, and reacts correctly.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255