ReentrantLock Scenarios and Examples
ReentrantLock Scenarios and Examples
Examples
1. Basic Locking with ReentrantLock
Use `lock()` and `unlock()` to define a critical section manually.
Example:
ReentrantLock lock = new ReentrantLock();
Example:
if (lock.tryLock()) {
try {
// do work
} finally {
lock.unlock();
}
} else {
System.out.println("Lock not available, doing something else...");
}
Example:
try {
if (lock.tryLock(2, TimeUnit.SECONDS)) {
try {
// critical section
} finally {
lock.unlock();
}
} else {
System.out.println("Couldn't acquire lock within 2 seconds");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Example:
try {
lock.lockInterruptibly();
try {
// critical section
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
System.out.println("Thread was interrupted while waiting for lock.");
}
5. Fair Locking
A fair ReentrantLock gives access to the longest-waiting thread.
Example:
ReentrantLock fairLock = new ReentrantLock(true); // fair policy
6. Reentrancy Support
A thread can acquire the same lock multiple times.
Example:
lock.lock();
lock.lock();
try {
// nested locking allowed
} finally {
lock.unlock();
lock.unlock(); // must unlock the same number of times
}
Bad example:
lock.lock();
doWork(); // might throw
lock.unlock(); // may never be reached!