Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Thread.currentThread().interrupt() be called?

I read a sample code given by Bloch in Effective Java as shown below:

enter image description here

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:

enter image description here

Can anyone explain it a step further?

like image 469
tuan long Avatar asked Dec 20 '22 19:12

tuan long


2 Answers

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).

like image 45
Darkhogg Avatar answered Jan 03 '23 03:01

Darkhogg


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.

like image 196
bowmore Avatar answered Jan 03 '23 03:01

bowmore