InterruptibleLocking.java
import java.util.concurrent.locks.*;
/**
* InterruptibleLocking
*
*/
public class InterruptibleLocking {
private static final int NUMBER_THREADS = 10;
public static void main(String[] args) {
InterruptibleLocking it = new InterruptibleLocking();
Thread[] ts = new Thread[NUMBER_THREADS];
for(int i = 0; i < NUMBER_THREADS; i++) {
int ii = i;
ts[i] = new Thread(() -> {
try {
it.sendOnSharedLine("send message "+ii);
} catch (InterruptedException e) {
System.out.println("get interrupted! " + ii);
//e.printStackTrace();
}
});
ts[i].start();
}
for(int i = 5; i < NUMBER_THREADS; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(ts[i].isAlive())
ts[i].interrupt();
}
System.out.println("Done!");
}
private Lock lock = new ReentrantLock();
public boolean sendOnSharedLine(String message)
throws InterruptedException {
lock.lockInterruptibly();
try {
return cancellableSendOnSharedLine(message);
} finally {
lock.unlock();
}
}
private boolean cancellableSendOnSharedLine(String message) throws InterruptedException {
/* send something */
Thread.sleep(1000);
System.out.println("sent " + message);
return true;
}
}
This program demonstrates interruptible locking using lock.lockInterruptibly()
, a feature of ReentrantLock
covered in Chapter 13 of Java Concurrency in Practice. Ten threads attempt to send messages through a shared line by acquiring a lock. Threads 5 through 9 are intentionally interrupted after a delay, which safely cancels their lock attempts without blocking them indefinitely. This technique is especially useful in systems where threads must remain responsive to cancellation signals, enabling more graceful interruption handling compared to synchronized
blocks, which do not support interruption during lock acquisition.
No comments:
Post a Comment