ReentrantLock in Java is an advanced synchronization mechanism that provides explicit locking with more flexibility and control than the synchronized keyword.
In simple words:
ReentrantLock allows threads to safely access shared resources while providing additional features such as fairness, timeout handling, interruptible locking, and multiple condition variables.
Why ReentrantLock was Introduced?
The synchronized keyword has limitations:
- No fairness guarantee
- No timeout support
- No interruptible lock waiting
- Limited flexibility
- No advanced lock management
Problem with synchronized
Thread Waits for Lock
|
v
Cannot Timeout
|
v
Cannot Interrupt Easily
|
v
Less Flexible Concurrency
Solution Provided by ReentrantLock
Thread Requests Lock
|
v
Advanced Lock Features Available
|
+-------> Fair Scheduling
|
+-------> Timeout Support
|
+-------> Interruptible Waiting
|
v
Better Concurrency Control
Main Package
java.util.concurrent.locks
What Does "Reentrant" Mean?
Reentrant means:
A thread holding the lock can acquire the same lock again without deadlocking itself.
Reentrant Behavior Example
Thread Acquires Lock
|
v
Same Thread Calls Another Locked Method
|
v
Lock Acquired Again Successfully
Basic ReentrantLock Example
import java.util.concurrent.locks.*;
class Counter {
private int count = 0;
private ReentrantLock lock =
new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
System.out.println(
count
);
}
finally {
lock.unlock();
}
}
}
Why try-finally Important?
Ensures lock is always released even if exceptions occur.
Locking Flow
Thread Requests Lock
|
v
lock() Acquires Lock
|
v
Critical Section Executes
|
v
unlock() Releases Lock
What is Critical Section?
Critical section is the code accessing shared resources.
Example
count++;
Difference Between synchronized and ReentrantLock
| Feature | synchronized | ReentrantLock |
|---|---|---|
| Fairness | No | Yes |
| Timeout Support | No | Yes |
| Interruptible Lock | No | Yes |
| Condition Variables | Single Monitor | Multiple Conditions |
| Flexibility | Limited | High |
1. Fair Lock
ReentrantLock supports fair scheduling.
Fair Lock Example
ReentrantLock lock =
new ReentrantLock(true);
What Does Fairness Mean?
Threads get lock in:
First Come First Serve (FIFO)
Fair Lock Flow
Thread 1 Requests Lock
Thread 2 Requests Lock
Thread 3 Requests Lock
|
v
Lock Granted in Arrival Order
2. tryLock()
Attempts to acquire lock without waiting forever.
tryLock() Example
if(lock.tryLock()) {
try {
System.out.println(
"Lock Acquired"
);
}
finally {
lock.unlock();
}
}
else {
System.out.println(
"Could Not Acquire Lock"
);
}
tryLock() Flow
Thread Requests Lock
|
YES | NO
|
v
Lock Acquired OR Immediate Failure
3. tryLock() with Timeout
Waits for limited time only.
Example
if(lock.tryLock(
5,
TimeUnit.SECONDS
)) {
try {
System.out.println(
"Lock Acquired"
);
}
finally {
lock.unlock();
}
}
Timeout Flow
Thread Waits for Lock
|
v
Timeout Reached?
|
YES | NO
|
v
Stop Waiting OR Acquire Lock
4. lockInterruptibly()
Allows waiting thread to be interrupted.
Example
lock.lockInterruptibly();
Interruptible Lock Flow
Thread Waiting for Lock
|
v
Interrupt Signal Received
|
v
InterruptedException Thrown
5. Condition Interface
ReentrantLock supports multiple condition variables.
Condition Example
Condition condition =
lock.newCondition();
Condition Methods
| Method | Purpose |
|---|---|
| await() | Wait for condition |
| signal() | Wake one thread |
| signalAll() | Wake all threads |
Condition Flow
Thread Calls await()
|
v
Thread Waits
|
v
Another Thread Calls signal()
|
v
Waiting Thread Resumes
Producer-Consumer Example Using ReentrantLock
import java.util.concurrent.locks.*;
class SharedBuffer {
private int data;
private boolean available = false;
private ReentrantLock lock =
new ReentrantLock();
private Condition condition =
lock.newCondition();
public void produce(
int value
) throws Exception {
lock.lock();
try {
while(available) {
condition.await();
}
data = value;
available = true;
System.out.println(
"Produced: " + value
);
condition.signalAll();
}
finally {
lock.unlock();
}
}
public void consume()
throws Exception {
lock.lock();
try {
while(!available) {
condition.await();
}
System.out.println(
"Consumed: " + data
);
available = false;
condition.signalAll();
}
finally {
lock.unlock();
}
}
}
Producer-Consumer Flow
Producer Acquires Lock
|
v
Data Added to Buffer
|
v
signalAll() Wakes Consumer
|
v
Consumer Processes Data
ReentrantLock in Banking Systems
Banking applications use ReentrantLock for:
- Transaction synchronization
- Account balance updates
- Fraud detection pipelines
- Concurrent payment processing
- Distributed transaction coordination
Banking Flow
Multiple Transactions Arrive
|
v
ReentrantLock Protects Account Data
|
v
Only One Transaction Updates Balance
|
v
Data Consistency Maintained
ReentrantLock in E-Commerce Systems
E-commerce platforms use ReentrantLock for:
- Inventory synchronization
- Order processing
- Payment coordination
- Coupon validation
- Concurrent cart updates
E-Commerce Flow
Multiple Users Buy Same Product
|
v
ReentrantLock Controls Inventory Access
|
v
Stock Updated Safely
ReentrantLock in Spring Boot
Spring Boot applications use ReentrantLock for:
- Concurrent service access
- Thread-safe caching
- Async processing
- Shared resource protection
- Distributed coordination
Spring Boot Flow
Multiple REST Requests Arrive
|
v
ReentrantLock Protects Shared Resource
|
v
Thread-Safe Processing Happens
ReentrantLock in Microservices
Microservices architectures use ReentrantLock concepts for:
- Distributed synchronization
- Event coordination
- Resource locking
- Thread-safe processing
- Reactive concurrency
Microservice Flow
Service Requests Shared Resource
|
v
Lock Coordination Happens
|
v
Concurrent Updates Controlled
Advantages of ReentrantLock
- More flexible than synchronized
- Supports fairness
- Supports timeout handling
- Supports interruptible locking
- Supports multiple conditions
- Better concurrency control
Disadvantages
- More complex than synchronized
- Manual unlock required
- Improper unlock causes bugs
- Slightly harder debugging
Common Interview Mistake
Many developers forget to call unlock().
Actually:
- Missing unlock() can create deadlocks.
Another Common Mistake
Many developers think ReentrantLock is always better than synchronized.
Actually:
- synchronized is simpler and sufficient for many scenarios.
Best Practices
- Always use try-finally with locks
- Prefer fair locks only when needed
- Use tryLock() to avoid deadlocks
- Keep critical sections small
- Avoid nested locking complexity
- Monitor lock contention in production
Realtime Enterprise Example
Online Ticket Booking Platform
Multiple Users Book Same Seat
|
v
ReentrantLock Controls Seat Access
|
v
Only One Booking Succeeds
|
v
Double Booking Prevented
Related Learning Topics
- What is Synchronization in Java
- What is Deadlock in Java
- What is Race Condition in Java
- What is Thread Starvation in Java
- What is Producer-Consumer Problem in Java
Professional Interview Answer
ReentrantLock is an advanced locking mechanism in Java provided by the java.util.concurrent.locks package that offers more flexibility and control than the synchronized keyword for thread synchronization and concurrency management. It is called "reentrant" because a thread already holding the lock can acquire the same lock again without deadlocking itself. ReentrantLock supports advanced features such as fair locking, timeout-based locking using tryLock(), interruptible locking using lockInterruptibly(), and multiple condition variables using the Condition interface. Enterprise applications, Spring Boot systems, banking platforms, distributed microservices, cloud-native architectures, Kafka consumers, high-concurrency systems, e-commerce platforms, and real-time distributed applications heavily use ReentrantLock for thread-safe resource access, transaction coordination, inventory synchronization, distributed processing, and scalable concurrency control. Although ReentrantLock provides advanced concurrency features, developers must carefully manage lock acquisition and release using try-finally blocks to avoid deadlocks and resource leaks.
Frequently Asked Questions
What is ReentrantLock in Java?
ReentrantLock is an advanced synchronization mechanism that provides explicit locking with additional concurrency features.
Why is it called reentrant?
Because the same thread can acquire the lock multiple times safely.
Which package contains ReentrantLock?
java.util.concurrent.locks
What are advantages of ReentrantLock over synchronized?
Fairness, timeout support, interruptible locking, and multiple conditions.
Where is ReentrantLock used heavily?
Banking systems, Spring Boot applications, distributed microservices, inventory systems, and high-concurrency enterprise platforms.