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?
interrupted() returns the interrupt status and also clears it. A thread which is blocked to acquire an intrinsic lock (BLOCKED state) cannot be interrupted. Similarly, when a thread acquires intrinsic lock, it cannot be interrupted.
interrupt() occurs while that thread is executing. The . interrupt() method sets the "interrupted" flag for that thread and interrupts any IO or sleep operations. It does nothing else, so it's up to your program to respond appropriately- and check its interrupt flag, via Thread.
interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException.
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.
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()
.
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