Actual use of lockInterruptibly for a ReentrantLock
The logic is the same as for all interruptible blocking methods: it allows the thread to immediately react to the interrupt
signal sent to it from another thread.
How this particular feature is used is up to the application design. For example, it can be used to kill a contingent of threads in a pool which are all waiting to aquire a lock.
Try to understand this concept through below code example.
Code Sample:
package codingInterview.thread;
import java.util.concurrent.locks.ReentrantLock;
public class MyRentrantlock {
Thread t = new Thread() {
@Override
public void run() {
ReentrantLock r = new ReentrantLock();
r.lock();
System.out.println("lock() : lock count :" + r.getHoldCount());
interrupt();
System.out.println("Current thread is intrupted");
r.tryLock();
System.out.println("tryLock() on intrupted thread lock count :" + r.getHoldCount());
try {
r.lockInterruptibly();
System.out.println("lockInterruptibly() --NOt executable statement" + r.getHoldCount());
} catch (InterruptedException e) {
r.lock();
System.out.println("Error");
} finally {
r.unlock();
}
System.out.println("lockInterruptibly() not able to Acqurie lock: lock count :" + r.getHoldCount());
r.unlock();
System.out.println("lock count :" + r.getHoldCount());
r.unlock();
System.out.println("lock count :" + r.getHoldCount());
}
};
public static void main(String str[]) {
MyRentrantlock m = new MyRentrantlock();
m.t.start();
System.out.println("");
}
}
Output:
lock() : lock count :1
Current thread is intrupted
tryLock() on intrupted thread lock count :2
Error
lockInterruptibly() not able to Acqurie lock: lock count :2
lock count :1
lock count :0
lockInterruptibly()
may block if the the lock is already held by another thread and will wait until the lock is aquired. This is the same as with regular lock()
. But if another thread interrupts the waiting thread lockInterruptibly()
will throw InterruptedException
.