I read a sample code given by Bloch in Effective Java as shown below:
Now, I want to make it clear that for which purpose Thread.currentThread().interrupt()
was called. I read explanation given by that book but I'm still confused:
Can anyone explain it a step further?
When a method like await()
is interrupted or called in an interrupted thread, the interrupted flag is cleared so subsequent calls don't immediately stop due to a previous interrupt.
To avoid this, the catch
clause re-interrupts the thread so the flag is still set and the code outside run
knows about it being interrupted and handles it appropriately (usually shutting down the worker).
When you catch an InterruptedException
, the thread's interrupted flag is cleared. By calling Thread.currentThread().interrupt()
, you set the interrupted flag again so clients higher up the stack know the thread has been interrupted and can react accordingly. In the example, the Executor
is one such client.
You may want to read this article for a more thorough explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With