ReentrantLock is a flexible locking mechanism provided by the java.util.concurrent.locks package for controlling access to shared resources in multithreaded applications. It offers all the capabilities of synchronized while providing additional features such as fairness policies, interruptible locking, timed lock acquisition, and non-blocking lock attempts. The term "reentrant" means that a thread holding the lock can acquire it multiple times without causing a deadlock.
Key Points: • ReentrantLock provides advanced features such as tryLock(), lockInterruptibly(), and configurable fairness policies that are not available with synchronized. • Unlike synchronized, locks must be explicitly acquired using lock() and released using unlock(), typically inside a finally block. • ReentrantLock offers greater flexibility and control, making it suitable for complex concurrency scenarios.
Example: Consider a banking application where multiple threads update account balances. Using ReentrantLock allows a thread to attempt lock acquisition with a timeout, preventing indefinite waiting and improving responsiveness under heavy load.
Code Example:
import java.util.concurrent.locks.ReentrantLock;
class BankAccount {
private int balance = 1000;
private final ReentrantLock lock =
new ReentrantLock();
public void withdraw(int amount) {
lock.lock();
try {
if (balance >= amount) {
balance -= amount;
System.out.println(
"Remaining Balance: "
+ balance);
}
} finally {
lock.unlock();
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account =
new BankAccount();
account.withdraw(200);
}
}Interview Tip: A concise interview answer is: ReentrantLock is an explicit locking mechanism that provides more control than synchronized. It supports features such as fairness policies, timed locking, interruptible lock acquisition, and tryLock(). Unlike synchronized, it requires manual lock() and unlock() management, making it more flexible for advanced concurrency scenarios.