tuan long
tuan long

Reputation: 603

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?

Upvotes: 5

Views: 3931

Answers (2)

bowmore
bowmore

Reputation: 11280

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.

Upvotes: 12

Darkhogg
Darkhogg

Reputation: 14165

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

Upvotes: 2

Related Questions