ReentrantLock tryLock Bounded Wait
Bound lock waits with ReentrantLock.tryLock(timeout): give up instead of blocking forever while another thread holds the lock, unlocking only on success.
Code
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class BoundedLockWait {
static final ReentrantLock LOCK = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
// 持有者 100ms 后释放:tryLock(1s) 在限期内等到锁
Thread holder = Thread.ofPlatform().start(() -> {
LOCK.lock();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
LOCK.unlock();
}
});
Thread.sleep(20);
boolean got = LOCK.tryLock(1, TimeUnit.SECONDS);
System.out.println("acquired after release: " + got);
if (got) {
LOCK.unlock();
}
holder.join();
// 长期占用时:tryLock(50ms) 到期放弃,而不是无限等待
Thread greedy = Thread.ofPlatform().start(() -> {
LOCK.lock();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
LOCK.unlock();
}
});
Thread.sleep(20);
boolean gave = LOCK.tryLock(50, TimeUnit.MILLISECONDS);
System.out.println("gave up instead of waiting: " + !gave);
if (gave) {
LOCK.unlock();
}
greedy.join();
}
}What the code does
The working surface is the class BoundedLockWait — everything else is wiring.
Applying it
Running the file prints labeled results such as acquired after release:, gave up instead of waiting: — each operation’s effect is visible in the output.
Statements that matter
Thread holder = Thread.ofPlatform().start(() -> {
LOCK.lock();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
LOCK.unlock();
}
});
Thread greedy = Thread.ofPlatform().start(() -> {
LOCK.lock();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
LOCK.unlock();
}
});
Thread.sleep(20);
Interactive Tools for This Topic
FAQ
- What does ReentrantLock tryLock Bounded Wait print when run?
- Execute the whole file; each printed line is prefixed with a label like `acquired after release:`, `gave up instead of waiting:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.