Actual use of lockInterruptibly for ReentrantLock

What do you actually use lockInterruptibly for this method? I read the API , but this is not very clear to me. Can someone put it in other words?

+12
java concurrency locking reentrantlock
source share
4 answers

The logic is the same as for all discontinuous locking methods: it allows a thread to immediately respond to an interrupt signal sent to it from another thread.

How this feature is used depends on the design of the application. For example, it can be used to destroy a contingent of threads in a pool that are all waiting for a lock.

+5
source share

lockInterruptibly() can be locked if the lock is already held by another thread and will wait until the lock is activated. This is the same as with regular lock() . But if another thread interrupts the waiting thread, lockInterruptibly() will throw an InterruptedException .

+8
source share

Try to understand this concept with the following code example.

Code example:

 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(); mtstart(); System.out.println(""); } } 

Exit:

 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 
0
source share

I just purposely came up with such a demonstration, but in fact I have no idea where exactly it can be used. Maybe this demo might help a bit :)

 private static void testReentrantLock() { ReentrantLock lock = new ReentrantLock(); Thread thread = new Thread(() -> { int i = 0; System.out.println("before entering ReentrankLock block"); try { lock.lockInterruptibly(); while (0 < 1) { System.out.println("in the ReentrankLock block counting: " + i++); } } catch (InterruptedException e) { System.out.println("ReentrankLock block interrupted"); } }); lock.lock(); thread.start(); thread.interrupt(); } 

Exit

 before entering ReentrankLock block ReentrankLock block interrupted 
0
source share

All Articles