Site Search:

TimedLocking.java

 TimedLocking.java

import java.util.concurrent.*;
import java.util.concurrent.locks.*;

import static java.util.concurrent.TimeUnit.NANOSECONDS;

/**
* TimedLocking
* <p/>
* Locking with a time budget
*
*/
public class TimedLocking {
public static void main(String[] args) {
TimedLocking tl = new TimedLocking();
for (int i = 0; i < 10; i++) {
final int messageIndex = i;
new Thread(() -> {
try {
tl.trySendOnSharedLine("message " + messageIndex, 1000000, NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
System.out.println("Done!");
}
private Lock lock = new ReentrantLock();

public boolean trySendOnSharedLine(String message,
long timeout, TimeUnit unit)
throws InterruptedException {
long nanosToLock = unit.toNanos(timeout)
- estimatedNanosToSend(message);
if (!lock.tryLock(nanosToLock, NANOSECONDS)) {
System.out.println("Failed to get lock");
return false;
}
try {
return sendOnSharedLine(message);
} finally {
lock.unlock();
}
}

private boolean sendOnSharedLine(String message) throws InterruptedException {
/* send something */
//Thread.sleep(1);
System.out.println("sent " + message);
return true;
}

long estimatedNanosToSend(String message) {
return message.length();
}
}

This program illustrates timed locking using ReentrantLock's tryLock(timeout, unit) method. Multiple threads attempt to send messages on a shared line, each trying to acquire the lock within a time budget adjusted for the estimated sending time. If the remaining time is insufficient to both acquire the lock and send the message, the attempt is aborted gracefully. This pattern is useful for maintaining responsiveness and avoiding deadlock in systems with strict time constraints or real-time requirements, allowing threads to proceed or fail fast rather than block indefinitely.

No comments:

Post a Comment