Locks — ReentrantLock & ReadWriteLock
java.util.concurrent locks: ReentrantLock, ReadWriteLock, Condition API
- Use ReentrantLock with tryLock() and timed locking
- Implement reader-writer concurrency with ReadWriteLock
- Replace wait/notify with the Condition API
Course:
Concept Encoding — Java Multithreading Series Topic: Locks in Java — ReentrantLock, ReadWriteLock, StampedLock, Semaphore, Condition Prerequisite Knowledge: synchronized keyword, Monitor Lock, Producer-Consumer Problem, Thread Basics
Table of Contents
- Quick Revision — synchronized and Monitor Lock
- Problem with synchronized — Why Custom Locks?
- Overview of Java Custom Locks
- 📌 ReentrantLock
- 📌 Shared Lock vs Exclusive Lock (Theory Foundation)
- 📌 ReadWriteLock
- 📌 Pessimistic vs Optimistic Locking
- 📌 StampedLock
- 📌 Semaphore
- 📌 Condition — Inter-Thread Communication with Custom Locks
- Comparison Table — All Lock Types
- Interview Notes
- Practice Questions
- Summary Revision Bullets
1. Quick Revision `synchronized` and Monitor Lock
Before diving into custom locks, it is essential to understand what synchronized does, because all custom locks are designed to solve its limitations.
What `synchronized` does
- When you mark a method or block as
synchronized, Java places a monitor lock on an object. - Only one thread at a time can hold the monitor lock of a given object.
- If a second thread tries to enter the same
synchronizedblock on the same object, it will block until the first thread releases the lock.
Key property: Monitor lock is tied to an Object
1class SharedResource {2 // Monitor lock is placed on 'this' object (the instance calling this method)3 public synchronized void produce(String threadName) {4 System.out.println("Lock acquired by: " + threadName);5 try {6 Thread.sleep(4000); // Hold lock for 4 seconds7 } catch (InterruptedException e) {8 e.printStackTrace();9 }10 System.out.println("Lock released by: " + threadName);11 }12}1public class Main {2 public static void main(String[] args) {3 SharedResource resource1 = new SharedResource(); // Object 14 SharedResource resource2 = new SharedResource(); // Object 25
6 Thread t1 = new Thread(() -> resource1.produce("Thread-1"));7 Thread t2 = new Thread(() -> resource2.produce("Thread-2"));8
9 t1.start();10 t2.start();11 }12}Lock acquired by: Thread-1 Lock acquired by: Thread-2 Lock released by: Thread-1 Lock released by: Thread-2
Why both threads ran simultaneously?
Because synchronized placed a monitor lock on resource1 for Thread-1 and a separate monitor lock on resource2 for Thread-2. They are different objects, so different locks — no blocking occurs.
synchronized is object-scoped. Two threads using two different objects of the same class will not block each other, even if the method is synchronized.2. Problem with `synchronized` Why Custom Locks?
The Real-World Requirement
In many production systems, you may have a critical section that should be accessed by only one thread at a time, regardless of how many different objects are involved.
Scenario:
- Thread-1 operates on
resource1(object 1) - Thread-2 operates on
resource2(object 2) - Both call the same critical method
- Requirement: Only one thread should be inside that critical section at any point in time
synchronized cannot solve this because its monitor lock is object-bound. If threads use different objects, they bypass each other's locks.
What We Need
A lock that is independent of objects — a standalone lock object that any number of objects/threads can share and respect.
java.util.concurrent.locks package provides — custom lock objects that are decoupled from any particular instance.3. Overview of Java Custom Locks
Java provides four primary types of custom locks in java.util.concurrent.locks (plus Semaphore in java.util.concurrent):
| Lock Type | Key Feature | Replaces |
|---|---|---|
ReentrantLock | Object-independent exclusive lock | synchronized |
ReadWriteLock | Multiple readers OR one writer | synchronized |
StampedLock | ReadWrite + Optimistic reads | ReadWriteLock |
Semaphore | N threads allowed simultaneously | synchronized (1 thread only) |
Condition | Thread communication with custom locks | wait() / notify() |
synchronized does. They depend on the lock object itself, which can be shared across multiple instances.4. ReentrantLock
Overview
ReentrantLock is the most fundamental custom lock. It provides the same mutual exclusion as synchronized, but with more control — and critically, it is not tied to any object instance.
Why This Concept Exists
Problem synchronized has:
- A
synchronizedmethod places a lock onthis(the calling object). - If two threads use different objects, they each get their own lock → no mutual exclusion.
What ReentrantLock solves:
- The lock is a standalone object you create.
- You pass this same lock object to all threads regardless of which class instance they're operating on.
- As long as all threads use the same lock object, only one thread can hold it at a time.
Definition
ReentrantLock is a class in java.util.concurrent.locks that implements the Lock interface. It provides explicit lock acquisition (lock()) and release (unlock()) methods. It is called "reentrant" because the same thread that holds the lock can re-acquire it without deadlocking itself (a feature called lock reentrancy).
Real-World Analogy
Think of ReentrantLock as a physical key to a server room:
- The key (lock object) is the authority — not the person (object instance).
- You can pass the same key to multiple departments.
- Whoever holds the key can enter. Others wait outside regardless of which department they're from.
Syntax
1import java.util.concurrent.locks.ReentrantLock;2
3ReentrantLock lock = new ReentrantLock();4
5lock.lock(); // Acquire the lock6try {7 // Critical section — only one thread can be here at a time8} finally {9 lock.unlock(); // Always release in finally block10}Syntax Breakdown
| Syntax | Meaning |
|---|---|
new ReentrantLock() | Creates a new lock object (unfair by default) |
lock.lock() | Acquires the lock; blocks if another thread holds it |
lock.unlock() | Releases the lock |
try { } finally { lock.unlock(); } | Ensures lock is released even if an exception occurs |
unlock() inside a finally block. If your critical section throws an exception and unlock() is not in finally, the lock will never be released, causing all other threads to block indefinitely (deadlock).Code Example Basic ReentrantLock
Step 1: The SharedResource class (without synchronized)
1import java.util.concurrent.locks.ReentrantLock;2
3class SharedResource {4
5 public void produce(String threadName, ReentrantLock lock) {6 lock.lock(); // Acquire the lock7 try {8 System.out.println("Lock acquired by: " + threadName);9 Thread.sleep(4000); // Simulate work10 System.out.println("Lock released by: " + threadName);11 } catch (InterruptedException e) {12 e.printStackTrace();13 } finally {14 lock.unlock(); // Always release15 }16 }17}Step 2: Main — passing the SAME lock to threads using DIFFERENT objects
1public class Main {2 public static void main(String[] args) {3 ReentrantLock sharedLock = new ReentrantLock(); // ONE lock object4
5 SharedResource resource1 = new SharedResource(); // Object 16 SharedResource resource2 = new SharedResource(); // Object 27
8 // Both threads use DIFFERENT objects but the SAME lock9 Thread t1 = new Thread(() -> resource1.produce("Thread-1", sharedLock));10 Thread t2 = new Thread(() -> resource2.produce("Thread-2", sharedLock));11
12 t1.start();13 t2.start();14 }15}Lock acquired by: Thread-1 Lock released by: Thread-1 Lock acquired by: Thread-2 Lock released by: Thread-2
Line-by-Line Explanation
| Line | Explanation |
|---|---|
ReentrantLock sharedLock = new ReentrantLock() | Creates one shared lock object used by all threads |
resource1.produce("Thread-1", sharedLock) | Thread-1 uses object resource1 but passes the shared lock |
resource2.produce("Thread-2", sharedLock) | Thread-2 uses object resource2 but passes the same lock |
lock.lock() | Thread tries to acquire. If another thread holds it, this thread blocks |
Thread.sleep(4000) | Simulates 4 seconds of critical work |
lock.unlock() inside finally | Guarantees release even on exception |
Step-by-Step Execution
- Main thread creates
sharedLock,resource1,resource2. - Thread-1 starts → calls
resource1.produce()→ callssharedLock.lock()→ acquires lock. - Thread-2 starts → calls
resource2.produce()→ callssharedLock.lock()→ blocks (lock held by Thread-1). - Thread-1 sleeps 4 seconds, then hits
finally→ callssharedLock.unlock()→ releases lock. - Thread-2 wakes up → acquires
sharedLock→ executes critical section. - Thread-2 finishes → calls
sharedLock.unlock().
Memory Representation
1Stack (Thread-1) Stack (Thread-2) Heap2┌────────────────┐ ┌────────────────┐ ┌─────────────────────┐3│ produce() │ │ produce() ──── │──────▶│ sharedLock object │4│ lock ref ─────│───────▶│ lock ref │ │ (ReentrantLock) │5│ threadName │ │ threadName │ │ owner: Thread-1 │6└────────────────┘ └────────────────┘ │ waitQueue: [T2] │7 └─────────────────────┘8 ┌──────────┐ ┌──────────┐9 │resource1 │ │resource2 │10 └──────────┘ └──────────┘resource1 and resource2 are different heap objects, but both threads reference the same sharedLock object. The lock does not care which object the thread came from.Why Is It Called "Reentrant"?
A reentrant lock allows the same thread to call lock() multiple times without deadlocking itself. Each lock() call must be paired with an unlock() call.
1ReentrantLock lock = new ReentrantLock();2
3public void outerMethod() {4 lock.lock();5 try {6 innerMethod(); // Same thread calls lock again — allowed!7 } finally {8 lock.unlock();9 }10}11
12public void innerMethod() {13 lock.lock(); // Same thread re-acquires its own lock — no deadlock14 try {15 // work16 } finally {17 lock.unlock();18 }19}synchronized in Java is also reentrant by default. The name ReentrantLock emphasizes this property explicitly.Common Mistakes
1// ❌ WRONG — unlock NOT in finally2lock.lock();3doWork(); // If this throws, lock is never released → DEADLOCK4lock.unlock();5
6// ✅ CORRECT7lock.lock();8try {9 doWork();10} finally {11 lock.unlock(); // Always executes12}Best Practices
- Always release in
finally. - Prefer
ReentrantLockoversynchronizedwhen you need: fairness, try-lock with timeout, lock polling, or object-independent locking. - Use
new ReentrantLock(true)for fair lock (threads acquire in order they requested; prevents starvation).
Key Observations
ReentrantLockis not tied to any object instance.- The lock is a standalone object that can be passed around.
- Multiple class instances can share the same lock.
- The lock tracks which thread holds it and a wait queue of blocked threads.
5. Shared Lock vs Exclusive Lock (Theory Foundation)
Overview
Two fundamental types of locks control concurrent access to resources:
Shared Lock (Read Lock)
- Multiple threads can hold a shared lock on the same resource simultaneously.
- Threads with shared lock can only read the resource — they must not modify it.
- If any thread holds a shared lock, no thread can acquire an exclusive lock until all shared locks are released.
Exclusive Lock (Write Lock)
- Only ONE thread can hold an exclusive lock at any time.
- The thread with exclusive lock can read AND write the resource.
- Exclusive lock can only be acquired when no other lock (shared or exclusive) is present on the resource.
- Once an exclusive lock is held, no other thread can acquire any lock (not even shared).
Compatibility Matrix
| Thread wants Shared Lock | Thread wants Exclusive Lock | |
|---|---|---|
| No lock currently held | ✅ Allowed | ✅ Allowed |
| Shared lock held by others | ✅ Allowed (multiple readers OK) | ❌ Not allowed |
| Exclusive lock held by another | ❌ Not allowed | ❌ Not allowed |
Real-World Analogy
Think of a library book:
- Shared lock = Multiple people can read the same book simultaneously (photocopy or digital). No one can modify it.
- Exclusive lock = One person takes the original book home to annotate it. No one else can even read it until they return it.
Diagram
Summary
6. ReadWriteLock
Overview
ReadWriteLock is a Java interface that maintains a pair of locks: one for read operations (shared) and one for write operations (exclusive). It directly implements the Shared Lock / Exclusive Lock theory.
Why This Concept Exists
In many real applications, reads vastly outnumber writes:
- 1000 users reading a product page vs. 10 admin users updating it.
- Dashboard showing analytics (high read) vs. data ingestion (low write).
With synchronized or ReentrantLock, even readers block each other, which is wasteful. ReadWriteLock solves this by allowing concurrent reads while still ensuring exclusive writes.
Definition
ReadWriteLock is an interface in java.util.concurrent.locks with two methods:
readLock()— returns the shared (read) lockwriteLock()— returns the exclusive (write) lock
Its primary implementation is ReentrantReadWriteLock.
When to Use ReadWriteLock
1Read requests >> Write requestsIf your application has very high reads and very low writes, ReadWriteLock significantly improves throughput by allowing multiple threads to read concurrently.
Syntax
1import java.util.concurrent.locks.ReadWriteLock;2import java.util.concurrent.locks.ReentrantReadWriteLock;3
4// Create the ReadWriteLock5ReadWriteLock rwLock = new ReentrantReadWriteLock();6
7// Acquiring READ lock (Shared)8rwLock.readLock().lock();9try {10 // Read-only operations11} finally {12 rwLock.readLock().unlock();13}14
15// Acquiring WRITE lock (Exclusive)16rwLock.writeLock().lock();17try {18 // Read or write operations19} finally {20 rwLock.writeLock().unlock();21}Syntax Breakdown
| Syntax | Meaning |
|---|---|
new ReentrantReadWriteLock() | Creates the ReadWriteLock implementation object |
rwLock.readLock() | Returns the shared read lock |
rwLock.writeLock() | Returns the exclusive write lock |
.lock() | Acquires the respective lock |
.unlock() | Releases the respective lock |
ReadWriteLock is an interface. ReentrantReadWriteLock is its concrete implementation. This is a standard Java design pattern.Code Example ReadWriteLock
1import java.util.concurrent.locks.ReadWriteLock;2import java.util.concurrent.locks.ReentrantReadWriteLock;3
4class SharedResource {5
6 // Producer uses READ lock (Shared)7 public void produce(String threadName, ReadWriteLock lock) {8 lock.readLock().lock(); // Acquire shared read lock9 try {10 System.out.println("Read lock acquired by: " + threadName);11 // Only read values here — do NOT modify shared state12 Thread.sleep(8000);13 System.out.println("Read lock released by: " + threadName);14 } catch (InterruptedException e) {15 e.printStackTrace();16 } finally {17 lock.readLock().unlock();18 }19 }20
21 // Consumer uses WRITE lock (Exclusive)22 public void consume(String threadName, ReadWriteLock lock) {23 lock.writeLock().lock(); // Acquire exclusive write lock24 try {25 System.out.println("Write lock acquired by: " + threadName);26 Thread.sleep(4000);27 System.out.println("Write lock released by: " + threadName);28 } catch (InterruptedException e) {29 e.printStackTrace();30 } finally {31 lock.writeLock().unlock();32 }33 }34}1public class Main {2 public static void main(String[] args) throws InterruptedException {3 ReadWriteLock rwLock = new ReentrantReadWriteLock();4
5 SharedResource res1 = new SharedResource();6 SharedResource res2 = new SharedResource();7 SharedResource res3 = new SharedResource();8
9 // Thread-1 and Thread-2: both want READ lock (shared)10 Thread t1 = new Thread(() -> res1.produce("Thread-1", rwLock));11 Thread t2 = new Thread(() -> res2.produce("Thread-2", rwLock));12
13 // Thread-3: wants WRITE lock (exclusive)14 Thread t3 = new Thread(() -> res3.consume("Thread-3", rwLock));15
16 t1.start();17 t2.start();18 Thread.sleep(1000); // Give t1, t2 time to acquire read locks first19 t3.start();20 }21}Read lock acquired by: Thread-1 Read lock acquired by: Thread-2 Read lock released by: Thread-1 Read lock released by: Thread-2 Write lock acquired by: Thread-3 Write lock released by: Thread-3
Step-by-Step Execution
- Thread-1 starts → acquires read lock (shared) → sleeping for 8 seconds.
- Thread-2 starts → acquires read lock (shared) — allowed because Thread-1 only has a shared lock.
- Thread-3 starts → tries to acquire write lock (exclusive) → BLOCKED because two shared locks are active.
- Thread-1 finishes → releases read lock.
- Thread-2 finishes → releases read lock.
- Now no locks are held → Thread-3 unblocks → acquires write lock → does work → releases.
Diagram
Key Observations
- Multiple threads can hold read locks simultaneously.
- Read lock = Shared lock = multiple readers allowed.
- Write lock = Exclusive lock = only one writer, no concurrent readers.
- Write lock can only be acquired when zero read locks AND zero write locks are held.
ReadWriteLock and can lead to data corruption.When to Use ReadWriteLock
1Use ReadWriteLock when:2 reads are much more frequent than writes3 4Avoid when:5 reads and writes are balanced (use ReentrantLock instead)6 write operations are very frequent (read starvation can occur)Best Practices
- Always use
try-finallyfor both read and write locks. - In the read section, never modify shared state.
- Consider
StampedLockfor higher-performance scenarios.
7. Pessimistic vs Optimistic Locking
StampedLock. It also directly maps to database locking strategies in system design interviews.Overview
There are two philosophies for handling concurrent access to shared data:
| Aspect | Pessimistic | Optimistic |
|---|---|---|
| Assumption | Conflicts are likely | Conflicts are rare |
| How it works | Lock first, then work | Work first, validate before commit |
| Lock held during work? | Yes | No |
| What happens on conflict | Thread blocks/waits | Rollback and retry |
| Best for | High contention | Low contention |
| Examples | synchronized, ReentrantLock, ReadWriteLock | StampedLock optimistic read, DB optimistic locking |
Pessimistic Locking
- Assumes that another thread will try to modify the data while you're working.
- So it acquires a lock before doing any work.
- Other threads are blocked until the lock is released.
- Safe but reduces concurrency.
All locks covered so far (synchronized, ReentrantLock, ReadWriteLock) are pessimistic.
Optimistic Locking
- Assumes that conflicts are rare.
- Does not acquire any lock before reading/working.
- Instead, it remembers the state/version of the data at the time it was read.
- Before writing/committing, it validates whether the state has changed since the read.
- If unchanged → proceed with the update ✅
- If changed → rollback and retry ❌
Real-World Example Database Row Version
This is the exact mechanism used in database optimistic locking (OCC — Optimistic Concurrency Control):
Database table:
| id | name | type | version |
|---|---|---|---|
| 123 | SJ | student | 1 |
| 456 | Ram | student | 1 |
version column: Starts at 1 when a row is inserted. Incremented by 1 on every update.
Scenario: Two threads want to update row 123 simultaneously.
How the version check works in SQL
1-- Thread-2's update (succeeds because version=1 matches)2UPDATE table 3SET type = 'x-student', version = version + 14WHERE id = 123 AND version = 1;5-- Returns: 1 row affected ✅6
7-- Thread-1's update (fails because version is now 2, not 1)8UPDATE table 9SET type = 'teacher', version = version + 110WHERE id = 123 AND version = 1;11-- Returns: 0 rows affected ❌ → Thread-1 must retryKey Points
- No lock is ever held during the processing time — other threads can read freely.
- Conflict is only detected at write time, not at read time.
- If conflict detected → rollback + retry (not block and wait).
- Very efficient under low contention because threads never block each other.
StampedLock's optimistic read implements internally in Java.8. StampedLock
Overview
StampedLock is the most powerful and feature-rich lock in Java's locking framework. It combines two capabilities:
- ReadWrite locking — same as
ReadWriteLock(shared read + exclusive write) - Optimistic reading — a lock-free read mode with version validation
Why This Concept Exists
ReadWriteLock still has a limitation: even readers must acquire a lock. In systems with extremely high read throughput, even acquiring a shared lock can be a bottleneck.
StampedLock's optimistic read allows threads to read without acquiring any lock at all — they simply validate afterward whether a write happened in the meantime.
The Stamp
A stamp is a long value returned by every lock operation in StampedLock. It represents the state/version of the lock at the time of acquisition.
- Like a "ticket number" or "row version" from the database analogy.
- Required when releasing the lock (
unlockmethods require the stamp). - Used by
validate(stamp)to check if a write has occurred since the stamp was issued.
Three Modes of StampedLock
Syntax All Three Modes
Mode 1: Write Lock (Exclusive)
1StampedLock lock = new StampedLock();2
3long stamp = lock.writeLock(); // Returns a stamp4try {5 // Exclusive write operation6} finally {7 lock.unlockWrite(stamp); // Pass the stamp back8}Mode 2: Read Lock (Shared)
1long stamp = lock.readLock(); // Returns a stamp2try {3 // Shared read operation4} finally {5 lock.unlockRead(stamp); // Pass the stamp back6}Mode 3: Optimistic Read (No Lock)
1long stamp = lock.tryOptimisticRead(); // Gets current state/version — NO lock acquired2// Perform read operations3if (lock.validate(stamp)) {4 // No write happened between tryOptimisticRead() and here → data is valid ✅5 // Proceed with results6} else {7 // A write happened → data may be stale ❌8 // Rollback / retry / fall back to regular read lock9}Syntax Breakdown
| Syntax | Meaning |
|---|---|
lock.writeLock() | Acquires exclusive write lock; returns stamp |
lock.readLock() | Acquires shared read lock; returns stamp |
lock.tryOptimisticRead() | Records current lock state, acquires NO lock; returns stamp |
lock.unlockWrite(stamp) | Releases write lock (stamp validates it's the correct release) |
lock.unlockRead(stamp) | Releases read lock |
lock.validate(stamp) | Returns true if no write lock was acquired since the stamp was issued |
readLock()/unlockRead() is technically needed for internal consistency and also for the optimistic read feature. During pessimistic read operations, it is still required syntactically even though it's less meaningful for validation there.Code Example StampedLock with Optimistic Read
1import java.util.concurrent.locks.StampedLock;2
3class SharedResource {4 private int value = 10; // Shared mutable data5 private final StampedLock lock = new StampedLock();6
7 // Producer: Uses OPTIMISTIC READ8 public void produce(String threadName) {9 long stamp = lock.tryOptimisticRead(); // No lock acquired10 System.out.println("Took optimistic read. Current value: " + value);11
12 // Perform some operation locally13 int newValue = value + 1; // Intend to update 10 → 1114
15 try {16 Thread.sleep(6000); // Simulate work — meanwhile consumer may write17 } catch (InterruptedException e) {18 e.printStackTrace();19 }20
21 // Validate: has any write lock been acquired since our optimistic read?22 if (lock.validate(stamp)) {23 // No write happened → safe to commit our change24 value = newValue;25 System.out.println("Optimistic read valid. Value updated to: " + value);26 } else {27 // A write happened → our data is stale → rollback28 value = 10; // Rollback to previous value29 System.out.println("Optimistic read INVALID. Rolled back. Value: " + value);30 }31 }32
33 // Consumer: Uses WRITE LOCK (Exclusive)34 public void consume(String threadName) {35 long stamp = lock.writeLock(); // Acquire exclusive write lock36 try {37 System.out.println("Write lock acquired by: " + threadName);38 Thread.sleep(2000);39 System.out.println("Write lock released by: " + threadName);40 } catch (InterruptedException e) {41 e.printStackTrace();42 } finally {43 lock.unlockWrite(stamp); // This changes the lock state → invalidates any optimistic stamps44 }45 }46}1public class Main {2 public static void main(String[] args) throws InterruptedException {3 SharedResource resource = new SharedResource();4
5 Thread producer = new Thread(() -> resource.produce("Thread-1"));6 Thread consumer = new Thread(() -> resource.consume("Thread-2"));7
8 producer.start();9 Thread.sleep(1000); // Let producer take optimistic read first10 consumer.start(); // Consumer acquires write lock while producer is "working"11 }12}Took optimistic read. Current value: 10 Write lock acquired by: Thread-2 Write lock released by: Thread-2 Optimistic read INVALID. Rolled back. Value: 10
Output (when no consumer runs):
1Took optimistic read. Current value: 102Optimistic read valid. Value updated to: 11Step-by-Step Execution (Conflict Scenario)
- Producer calls
tryOptimisticRead()→ gets stamp (e.g.,256). No lock acquired. - Producer reads
value = 10, prepares to set it to11, then sleeps 6 seconds. - Consumer calls
lock.writeLock()→ acquires exclusive lock → does work → callslock.unlockWrite(stamp). - Internally,
StampedLockincrements its version counter when the write lock is acquired/released. - Producer wakes up → calls
lock.validate(256). validatechecks: "Is the current version still compatible with stamp256?" → No, version changed → returnsfalse.- Producer rolls back
valueto10.
Internal Mechanism How validate() Works
1StampedLock maintains an internal 64-bit state variable.2
3When tryOptimisticRead() is called:4 → Returns current state (the stamp)5
6When writeLock() is acquired and released:7 → Internal state is modified (version bits change)8
9When validate(stamp) is called:10 → Compares current state with the saved stamp11 → If they are compatible (no write occurred): returns true12 → If write occurred (state changed): returns falseThis is directly analogous to the database row version mechanism described in section 7.
Code Example StampedLock ReadWrite Mode
1class SharedResourceRW {2
3 public void produce(String threadName, StampedLock lock) {4 long stamp = lock.readLock(); // Acquire shared read lock5 try {6 System.out.println("Read lock acquired by: " + threadName);7 Thread.sleep(4000);8 } catch (InterruptedException e) {9 e.printStackTrace();10 } finally {11 lock.unlockRead(stamp); // Must pass the stamp12 }13 }14
15 public void consume(String threadName, StampedLock lock) {16 long stamp = lock.writeLock(); // Acquire exclusive write lock17 try {18 System.out.println("Write lock acquired by: " + threadName);19 Thread.sleep(2000);20 } catch (InterruptedException e) {21 e.printStackTrace();22 } finally {23 lock.unlockWrite(stamp);24 }25 }26}The behavior is identical to ReadWriteLock — the difference is the stamp parameter required in unlock methods.
Key Observations
StampedLockis NOT reentrant — unlikeReentrantLockorReentrantReadWriteLock.- Optimistic read requires no unlock call — because no lock was acquired.
validate()is the equivalent of the DB version check.- When
validate()returnsfalse, you should fall back to a regular read lock or retry.
StampedLock does not support Condition. You cannot use await()/signal() with StampedLock.StampedLock is not reentrant, if the same thread tries to acquire the same write lock twice, it will deadlock.When to Use StampedLock
- When you have very high read throughput and writes are very rare.
- When you want lock-free reads with validation semantics.
- Provides better performance than
ReentrantReadWriteLockunder read-heavy conditions.
9. Semaphore
Overview
Semaphore is a concurrency primitive that controls how many threads can access a resource simultaneously. Unlike the previous locks that allow only one thread at a time, a semaphore has a configurable number of permits.
Why This Concept Exists
All previous locks allow exactly 1 thread inside the critical section at a time. But some real-world resources can be accessed by multiple threads simultaneously — just not unlimited threads.
Examples:
- 2 printers available → Allow max 2 threads to print simultaneously.
- 5 database connections in pool → Allow max 5 threads to use a connection.
- Rate limiting → Allow max N requests per second.
Definition
A Semaphore maintains a set of permits. Each acquire() call takes a permit; each release() call returns one. If no permits are available, the calling thread blocks until a permit becomes available.
This concept originated from Operating Systems (Dijkstra's semaphore) and works identically in Java.
Real-World Analogy
Think of a parking lot with a fixed number of spaces:
permits = 5→ 5 parking spaces.acquire()→ A car takes a space.release()→ A car leaves, freeing a space.- If all 5 spaces are full, new cars wait outside until someone leaves.
Syntax
1import java.util.concurrent.Semaphore;2
3// Create semaphore with N permits (N threads can run concurrently)4Semaphore semaphore = new Semaphore(2); // 2 permits = 2 threads at a time5
6// Acquiring a permit (equivalent to lock)7semaphore.acquire();8try {9 // Critical section — up to N threads can be here simultaneously10} catch (InterruptedException e) {11 e.printStackTrace();12} finally {13 semaphore.release(); // Release the permit14}Syntax Breakdown
| Syntax | Meaning |
|---|---|
new Semaphore(n) | Creates semaphore with n permits |
semaphore.acquire() | Decrements permit count; blocks if count = 0 |
semaphore.release() | Increments permit count; unblocks a waiting thread |
new Semaphore(n, true) | Fair semaphore — threads acquire permits in FIFO order |
Code Example Semaphore with 2 permits, 4 threads
1import java.util.concurrent.Semaphore;2
3class SharedResource {4 private final Semaphore semaphore;5
6 public SharedResource(int permits) {7 this.semaphore = new Semaphore(permits); // 2 permits8 }9
10 public void produce(String threadName) {11 try {12 semaphore.acquire(); // Acquire a permit (blocks if 0 available)13 System.out.println("Lock acquired by: " + threadName);14 Thread.sleep(4000); // Simulate work15 System.out.println("Lock released by: " + threadName);16 } catch (InterruptedException e) {17 e.printStackTrace();18 } finally {19 semaphore.release(); // Always release the permit20 }21 }22}1public class Main {2 public static void main(String[] args) {3 SharedResource resource = new SharedResource(2); // Only 2 threads at a time4
5 // 4 threads competing for 2 permits6 Thread t1 = new Thread(() -> resource.produce("Thread-1"));7 Thread t2 = new Thread(() -> resource.produce("Thread-2"));8 Thread t3 = new Thread(() -> resource.produce("Thread-3"));9 Thread t4 = new Thread(() -> resource.produce("Thread-4"));10
11 t1.start();12 t2.start();13 t3.start();14 t4.start();15 }16}Lock acquired by: Thread-1 Lock acquired by: Thread-2 Lock released by: Thread-2 Lock acquired by: Thread-3 Lock released by: Thread-1 Lock acquired by: Thread-4 Lock released by: Thread-3 Lock released by: Thread-4
Step-by-Step Execution
- Thread-1 calls
acquire()→ permits: 2 → 1. Enters critical section. - Thread-2 calls
acquire()→ permits: 1 → 0. Enters critical section. - Thread-3 calls
acquire()→ permits: 0 → BLOCKED. - Thread-4 calls
acquire()→ permits: 0 → BLOCKED. - Thread-2 finishes → calls
release()→ permits: 0 → 1. Thread-3 unblocks. - Thread-3 enters critical section.
- Thread-1 finishes → calls
release()→ permits: 0 → 1 (Thread-3 holds one). Thread-4 unblocks. - And so on...
Diagram
Connection Pool Analogy in Code
1// Simulating a DB connection pool with Semaphore2Semaphore connectionPool = new Semaphore(5); // Max 5 DB connections3
4public Connection getConnection() throws InterruptedException {5 connectionPool.acquire(); // Wait for an available connection6 return pool.checkoutConnection();7}8
9public void releaseConnection(Connection conn) {10 pool.checkinConnection(conn);11 connectionPool.release(); // Free up a slot12}Key Observations
Semaphore(1)behaves like a mutex (mutual exclusion lock) — equivalent toReentrantLock.Semaphore(n)where n > 1 allows concurrent access by n threads.- Unlike
ReentrantLock, a semaphore is not reentrant by default — the same thread can acquire multiple permits (reducing the count each time). - Semaphore does not track which thread acquired it — any thread can release a permit.
Semaphore doesn't track ownership, one thread can release another thread's permit. This is powerful but dangerous if misused. Use carefully.Best Practices
- Always release in
finally. - Use
new Semaphore(n, true)for fairness when thread starvation is a concern. - Semaphore is ideal for resource pool management and rate limiting.
When to Use Semaphore
| Scenario | Semaphore Permits |
|---|---|
| Only 1 thread at a time (mutex) | 1 |
| 2 printers, 2 threads max | 2 |
| DB connection pool of size 5 | 5 |
| API rate limit: 10 concurrent requests | 10 |
10. Condition Inter-Thread Communication with Custom Locks
Overview
When using synchronized, Java provides wait(), notify(), and notifyAll() for inter-thread communication. These methods are tied to the monitor lock of an object.
Since custom locks (ReentrantLock, ReadWriteLock, etc.) do not use monitor locks, wait() and notify() cannot be used with them. The equivalent mechanism is the Condition interface.
Why This Concept Exists
| Mechanism | Works With |
|---|---|
wait() / notify() / notifyAll() | synchronized (monitor lock) |
await() / signal() / signalAll() | Condition (custom locks) |
When you move from synchronized to ReentrantLock (for object-independent locking), you lose wait/notify. Condition fills that gap with exactly equivalent semantics.
Definition
Condition is an interface in java.util.concurrent.locks that provides thread waiting and signaling functionality. A Condition is always associated with a specific Lock object. A thread must hold the lock before calling await() or signal().
Method Mapping
synchronized + Object | ReentrantLock + Condition | Behavior |
|---|---|---|
object.wait() | condition.await() | Release lock, wait to be signaled |
object.notify() | condition.signal() | Wake one waiting thread |
object.notifyAll() | condition.signalAll() | Wake all waiting threads |
Syntax
1import java.util.concurrent.locks.Condition;2import java.util.concurrent.locks.ReentrantLock;3
4ReentrantLock lock = new ReentrantLock();5Condition condition = lock.newCondition(); // Condition is tied to this lock6
7// In one thread (Producer waiting):8lock.lock();9try {10 while (alreadyAvailable) {11 condition.await(); // Releases lock and waits12 }13 // Produce14 condition.signal(); // Signal consumer15} finally {16 lock.unlock();17}18
19// In another thread (Consumer):20lock.lock();21try {22 while (notAvailable) {23 condition.await();24 }25 // Consume26 condition.signal(); // Signal producer27} finally {28 lock.unlock();29}Syntax Breakdown
| Syntax | Meaning |
|---|---|
lock.newCondition() | Creates a Condition bound to this lock |
condition.await() | Releases the lock and waits; re-acquires lock when signaled |
condition.signal() | Wakes up one thread waiting on this condition |
condition.signalAll() | Wakes up all threads waiting on this condition |
await() or signal(). Otherwise, IllegalMonitorStateException is thrown — same rule as wait()/notify().Code Example Producer-Consumer with Condition
1import java.util.concurrent.locks.Condition;2import java.util.concurrent.locks.ReentrantLock;3
4class SharedBuffer {5 private int value = 0;6 private boolean available = false; // Is there data to consume?7 8 private final ReentrantLock lock = new ReentrantLock();9 private final Condition condition = lock.newCondition();10
11 // Producer: adds a value12 public void produce(int val) {13 lock.lock();14 try {15 // If already has value, wait for consumer to consume it16 while (available) {17 System.out.println("Producer waiting — buffer full");18 condition.await(); // Release lock and wait19 }20 this.value = val;21 this.available = true;22 System.out.println("Produced: " + val);23 condition.signal(); // Notify consumer24 } catch (InterruptedException e) {25 e.printStackTrace();26 } finally {27 lock.unlock();28 }29 }30
31 // Consumer: takes the value32 public void consume() {33 lock.lock();34 try {35 // If nothing available, wait for producer36 while (!available) {37 System.out.println("Consumer waiting — buffer empty");38 condition.await(); // Release lock and wait39 }40 System.out.println("Consumed: " + value);41 available = false;42 condition.signal(); // Notify producer43 } catch (InterruptedException e) {44 e.printStackTrace();45 } finally {46 lock.unlock();47 }48 }49}1public class Main {2 public static void main(String[] args) {3 SharedBuffer buffer = new SharedBuffer();4
5 Thread producer = new Thread(() -> {6 for (int i = 1; i <= 5; i++) {7 buffer.produce(i);8 }9 });10
11 Thread consumer = new Thread(() -> {12 for (int i = 0; i < 5; i++) {13 buffer.consume();14 }15 });16
17 producer.start();18 consumer.start();19 }20}Produced: 1 Consumed: 1 Produced: 2 Consumed: 2 Produced: 3 Consumed: 3 ...
Step-by-Step Execution
- Producer acquires lock →
available = false→ produces value 1 → setsavailable = true→ callscondition.signal()→ releases lock. - Consumer (was waiting on
condition.await()) wakes up → re-acquires lock → consumes value → setsavailable = false→ callscondition.signal()→ releases lock. - Producer wakes up → produces next value → cycle continues.
Sequence Diagram
Key Observations
Conditionis created vialock.newCondition()— it is bound to that specific lock.- You can create multiple conditions from one lock for more granular signaling (e.g., separate
notFullandnotEmptyconditions in a bounded buffer). condition.await()internally releases the lock (just likewait()releases the monitor).condition.signal()does not immediately give control to the signaled thread — it just moves it from the wait set to the ready queue.
ReentrantLock + Condition has over synchronized + wait/notify. For example, in LinkedBlockingQueue, separate conditions are used for "not full" and "not empty", avoiding unnecessary wake-ups.Common Mistake
1// ❌ WRONG — calling await() without holding the lock2condition.await(); // Throws IllegalMonitorStateException3
4// ✅ CORRECT5lock.lock();6try {7 condition.await(); // Must hold lock before await8} finally {9 lock.unlock();10}11. Comparison Table All Lock Types
| Feature | synchronized | ReentrantLock | ReadWriteLock | StampedLock | Semaphore |
|---|---|---|---|---|---|
| Lock type | Monitor | Exclusive | Shared/Exclusive | Shared/Exclusive/Optimistic | Counting |
| Object-dependent? | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
| Multiple threads allowed? | ❌ 1 only | ❌ 1 only | ✅ Multiple readers | ✅ Multiple readers | ✅ N threads |
| Reentrant? | ✅ Yes | ✅ Yes | ✅ Yes | ❌ No | ❌ No |
| Optimistic read? | ❌ No | ❌ No | ❌ No | ✅ Yes | ❌ No |
| Inter-thread comm | wait/notify | Condition.await/signal | Condition.await/signal | ❌ Not supported | ❌ Not supported |
| Fairness option? | ❌ No | ✅ Yes | ✅ Yes | ❌ No | ✅ Yes |
| Returns stamp? | ❌ No | ❌ No | ❌ No | ✅ Yes | ❌ No |
| Use case | Simple sync | Object-indep. exclusion | Read-heavy | High perf reads | Resource pools |
12. Interview Notes
Frequently Asked Questions
Q1: What is the difference between synchronized and ReentrantLock?
| Point | synchronized | ReentrantLock |
|---|---|---|
| Lock type | Monitor (implicit) | Explicit lock object |
| Object-dependency | Tied to object | Independent |
| Fairness | No | Yes (new ReentrantLock(true)) |
| Interruptibility | No | Yes (lockInterruptibly()) |
| Try-lock | No | Yes (tryLock()) |
| Condition support | wait/notify | Condition.await/signal |
| Auto-release | Yes (block scope) | No (must call unlock) |
Q2: What is a Shared Lock vs Exclusive Lock?
- Shared Lock (Read Lock): Multiple threads can hold it simultaneously; used for read-only access. No exclusive lock allowed while shared lock is held.
- Exclusive Lock (Write Lock): Only one thread can hold it; used for read+write. No other lock (shared or exclusive) can be held concurrently.
Q3: What is Optimistic Locking? How is it different from Pessimistic Locking?
- Pessimistic: Assumes conflict — acquires lock before work. Thread blocks if lock unavailable.
- Optimistic: Assumes no conflict — reads without lock, records version, validates before write. On version mismatch, rolls back and retries.
Q4: When would you use ReadWriteLock over ReentrantLock?
When reads significantly outnumber writes. ReadWriteLock allows concurrent reads, improving throughput. If reads and writes are balanced, ReentrantLock is simpler.
Q5: What is StampedLock? How does tryOptimisticRead work?
StampedLock provides read/write locks plus optimistic reading. tryOptimisticRead() returns a stamp (version number) without acquiring any lock. After performing a read, validate(stamp) checks if any write occurred in the interim. If false, rollback and retry with a proper read lock.
Q6: What is a Semaphore? How is it different from a lock?
A semaphore allows N threads to access a resource simultaneously (controlled by permit count). A lock allows only 1 thread. Semaphore(1) is functionally a mutex. Semaphores are not ownership-based — any thread can release.
Q7: Why can't we use wait() and notify() with ReentrantLock?
wait() and notify() are methods on Object and operate on the monitor lock (acquired via synchronized). ReentrantLock does not use monitor locks. Instead, use Condition condition = lock.newCondition() and call condition.await() / condition.signal().
Q8: What is the stamp in StampedLock?
A long value representing the lock state/version at the time of acquisition. Required to release the lock. Also used by validate() to detect if any write occurred since the stamp was issued — analogous to database row version.
Q9: What are the four types of custom locks in Java?
ReentrantLock— Object-independent exclusive lockReadWriteLock/ReentrantReadWriteLock— Shared read + exclusive writeStampedLock— ReadWrite + optimistic readingSemaphore— Counting lock allowing N concurrent threads
Q10: How does optimistic locking relate to database concurrency control?
Both use a version/stamp mechanism. In databases, a version column is checked on update (WHERE version = ?). In StampedLock, validate(stamp) checks if the internal state changed. Both avoid locks during reads and validate before writes.
Tricky Points
StampedLock is not reentrant — the same thread acquiring the same lock twice will deadlock.
- StampedLock does not support Condition.
- Semaphore.release() can be called by a different thread than the one that called acquire().
- During ReadWriteLock read section, never modify shared data — you only have a shared lock.
- condition.await() can wake up spuriously (without signal()) — always use while loop, not if.13. Practice Questions
Easy
- What is the difference between a monitor lock and a
ReentrantLock? - Can two threads simultaneously hold a read lock on the same
ReadWriteLock? - What happens if you call
lock.unlock()without callinglock.lock()first? - What does
Semaphore(3)mean? - What is the Java equivalent of
wait()when usingReentrantLock?
Medium
- Write a thread-safe counter class using
ReentrantLockinstead ofsynchronized. - Implement a simple read-heavy cache using
ReadWriteLockwhere reads are concurrent but writes are exclusive. - Explain with code how
StampedLock.tryOptimisticRead()andvalidate()work together. - Create a
ConnectionPoolclass usingSemaphorethat allows max 3 concurrent connections. - Rewrite a producer-consumer problem using
ReentrantLockandCondition(nowait/notify).
Hard
- Why might
ReentrantReadWriteLocklead to writer starvation? How can you avoid it? - Implement a bounded blocking queue using
ReentrantLockwith two separateConditionobjects — one for "not full" and one for "not empty". - Explain the internal stamp mechanism of
StampedLock. When wouldvalidate()returnfalse? - Compare
StampedLockandReadWriteLockin terms of performance characteristics. When would you prefer each? - Design a thread-safe LRU cache using
ReadWriteLockorStampedLock. Discuss your choice.
14. Summary Revision Bullets
synchronized (Baseline)
- Puts a monitor lock on the calling object.
- Two threads with different objects → different locks → no mutual exclusion.
- Inter-thread communication:
wait()/notify()/notifyAll().
ReentrantLock
- Object-independent exclusive lock.
- Pass the same lock object to multiple threads/instances.
- Use
lock()andunlock()(always infinally). - Inter-thread communication:
Condition(await()/signal()). - Supports fairness (
new ReentrantLock(true)).
Shared Lock vs Exclusive Lock
- Shared (Read) Lock: Multiple threads can hold; read-only; blocks exclusive.
- Exclusive (Write) Lock: Only one thread; read+write; blocks all other locks.
- Exclusive requires: zero shared locks AND zero exclusive locks on resource.
ReadWriteLock
- Interface:
readLock()andwriteLock(). - Implementation:
ReentrantReadWriteLock. - Multiple readers concurrently → better throughput for read-heavy workloads.
- One writer at a time; no concurrent readers while writing.
Pessimistic vs Optimistic Locking
- Pessimistic: Lock first, work, unlock. Threads block on conflict.
- Optimistic: Work without lock, record version, validate before commit. Rollback + retry on conflict.
- DB uses
versioncolumn; Java usesstamp.
StampedLock
- Supports: Write Lock, Read Lock, Optimistic Read.
- Every operation returns a stamp (version token).
tryOptimisticRead()→ no lock acquired; returns stamp.validate(stamp)→trueif no write happened since stamp;false→ rollback.- Not reentrant. Does not support
Condition.
Semaphore
- Controls how many threads access a resource:
new Semaphore(n). acquire()decrements permits; blocks at 0.release()increments permits; unblocks waiter.- Use for: connection pools, resource limiting, rate control.
- Any thread can
release()— not ownership-based.
Condition
- Required for inter-thread communication with custom locks.
- Created via:
lock.newCondition(). await()=wait(),signal()=notify(),signalAll()=notifyAll().- Thread must hold the lock before calling
await()orsignal(). await()releases the lock (likewait()releases the monitor).
End of Study Guide — Java Multithreading Locks
Mastery check
How well can you recall this?
Finished this lesson?