wanghao
wanghao

Reputation: 391

Why can't Thread.interrupt() interrupt a thread trying to acquire lock

In the book Thinking in Java it is written that Thread.interrupt() cannot interrupt a thread which is trying to acquire a synchronized lock, I want to know why?

Upvotes: 5

Views: 2596

Answers (2)

user207421
user207421

Reputation: 310998

The book is wrong, unless it is only referring to the synchronized keyword. Object.wait() throws InterruptedException.

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200166

A blocking operation can be interrupted only if it is declared to throw InterruptedException. Clearly, a synchronized block does not declare it, therefore it is impossible to interrupt a thread while it is waiting to acquire a lock.

Alternatively you can use an explicit lock and call Lock.lockInterruptibly().

Upvotes: 9

Related Questions