Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 952
wanghao Avatar asked Aug 15 '15 11:08

wanghao


People also ask

Can we interrupt a thread that is blocked as a result of trying to acquire an intrinsic lock?

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.

What happens when you call interrupt () on a running thread?

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.

Does thread interrupt terminate a 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.

What does interrupt () do in Java?

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.


1 Answers

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

like image 154
Marko Topolnik Avatar answered Sep 29 '22 12:09

Marko Topolnik