Advanced Locks — StampedLock & Semaphore
StampedLock optimistic reads, Semaphore, CountDownLatch, CyclicBarrier, Phaser
- Apply StampedLock for high-throughput read-heavy scenarios
- Use Semaphore to limit concurrent access to a resource
- Coordinate threads with CountDownLatch and CyclicBarrier
Series Context:
This is Part 3 of the Java Multithreading series. It assumes you understand synchronized, monitor locks, wait(), notify(), and the thread lifecycle from Parts 1 & 2. This guide covers advanced custom locking mechanisms and inter-thread communication without synchronized.
Table of Contents
- Why Custom Locks? The Problem with synchronized
- Overview of Lock Types
- ReentrantLock
- Shared Lock vs Exclusive Lock
- ReadWriteLock
- Pessimistic vs Optimistic Locking
- StampedLock
- Semaphore
- Inter-Thread Communication with Custom Locks — Condition
- Full Comparison Table
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary
1. Why Custom Locks? The Problem with `synchronized`
1.1 Recap How `synchronized` Monitor Lock Works
When you place synchronized on a method or block, Java puts a monitor lock on the specific object that called the method. Only one thread at a time can hold the monitor lock for a given object.
1class SharedResource {2 synchronized void produce() {3 System.out.println("Lock acquired by: " + Thread.currentThread().getName());4 try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); }5 System.out.println("Lock released by: " + Thread.currentThread().getName());6 }7}1SharedResource resource1 = new SharedResource();2SharedResource resource2 = new SharedResource(); // DIFFERENT object3
4Thread t1 = new Thread(() -> resource1.produce()); // monitor lock on resource15Thread t2 = new Thread(() -> resource2.produce()); // monitor lock on resource26
7t1.start();8t2.start();Lock acquired by: Thread-0 Lock acquired by: Thread-1 ← Both acquired simultaneously! Lock released by: Thread-0 Lock released by: Thread-1
Both threads entered the critical section at the same time because the monitor lock is per-object — resource1 and resource2 are different objects with independent locks.
1.2 The Real-World Problem
In many real-world scenarios, multiple threads use different objects but access the same critical code. You need a lock that:
"No matter which object created you, no matter how many objects exist — only one thread (or a controlled number) may enter this critical section at a time."
synchronized cannot do this. This is exactly where custom locks come in.
2. Overview of Lock Types
| Lock Type | Package | Key Feature | Use Case |
|---|---|---|---|
ReentrantLock | java.util.concurrent.locks | Replaces synchronized; object-independent lock | Any scenario where synchronized doesn't suffice |
ReadWriteLock | java.util.concurrent.locks | Multiple readers OR one exclusive writer | Read-heavy workloads |
StampedLock | java.util.concurrent.locks | Read/write lock + optimistic reading | Very high read throughput; optimistic concurrency |
Semaphore | java.util.concurrent | Allows N threads into critical section simultaneously | Connection pools, resource throttling |
java.util.concurrent (JUC), introduced in Java 5. They are not based on monitor locks — they use their own internal locking state.3. ReentrantLock
3.1 What Is ReentrantLock?
ReentrantLock is the most direct replacement for synchronized. Unlike synchronized, the lock is not tied to any specific object — it is its own independent object. Any thread that holds a reference to the same ReentrantLock instance must compete for it.
The name "reentrant" means that the same thread that holds the lock can acquire it again (re-enter a locked section) without deadlocking itself. synchronized is also reentrant for the same reason.
3.2 Key Methods
| Method | Description |
|---|---|
lock() | Acquires the lock. Blocks if another thread holds it. |
unlock() | Releases the lock. Must be called in a finally block. |
tryLock() | Tries to acquire the lock. Returns true if acquired, false otherwise. Non-blocking. |
tryLock(long time, TimeUnit unit) | Like tryLock() but waits up to the given timeout. |
lockInterruptibly() | Acquires lock but can be interrupted while waiting. |
isLocked() | Returns true if the lock is held by any thread. |
getHoldCount() | Returns the number of times the current thread holds this lock (reentrancy count). |
3.3 Why `unlock()` Must Always Be in `finally`
If an exception is thrown inside the locked section and unlock() is not in finally, the lock is never released — causing all waiting threads to hang forever (deadlock).
1lock.lock();2try {3 // critical section — exception might happen here4 riskyOperation();5} finally {6 lock.unlock(); // ALWAYS runs, even if exception thrown7}3.4 Solving the Multi-Object Problem with ReentrantLock
1import java.util.concurrent.locks.ReentrantLock;2
3class SharedResource {4 void produce(ReentrantLock lock) {5 lock.lock(); // acquire the lock — independent of 'this' object6 try {7 System.out.println("Lock acquired by: " + Thread.currentThread().getName());8 Thread.sleep(4000);9 System.out.println("Lock released by: " + Thread.currentThread().getName());10 } catch (InterruptedException e) {11 Thread.currentThread().interrupt();12 } finally {13 lock.unlock(); // always release14 }15 }16}1public class ReentrantLockDemo {2 public static void main(String[] args) {3 ReentrantLock sharedLock = new ReentrantLock(); // ONE shared lock object4
5 SharedResource resource1 = new SharedResource(); // different objects6 SharedResource resource2 = new SharedResource();7
8 Thread t1 = new Thread(() -> resource1.produce(sharedLock));9 Thread t2 = new Thread(() -> resource2.produce(sharedLock));10
11 t1.start();12 t2.start();13 }14}Lock acquired by: Thread-0 [... 4 seconds ...] Lock released by: Thread-0 Lock acquired by: Thread-1 [... 4 seconds ...] Lock released by: Thread-1
Thread-1 waited even though it used a different object — because both threads compete on the same ReentrantLock instance, not on object monitor locks.
3.5 Internal Execution Flow
3.6 tryLock() Non-Blocking Lock Attempt
1if (lock.tryLock()) {2 try {3 // do work4 } finally {5 lock.unlock();6 }7} else {8 System.out.println("Lock not available — doing something else");9}tryLock() never blocks — useful when you want the thread to do alternate work if the lock is busy.
3.7 Fair vs Unfair ReentrantLock
By default, ReentrantLock is unfair — threads are not guaranteed to acquire the lock in the order they requested it (better throughput, but possible starvation).
1ReentrantLock fairLock = new ReentrantLock(true); // fair — FIFO order2ReentrantLock unfairLock = new ReentrantLock(false); // default — unfairsynchronized is also unfair.
4. Shared Lock vs Exclusive Lock
Before studying ReadWriteLock and StampedLock, you must understand these two fundamental lock categories.
4.1 Shared Lock (Read Lock)
- Multiple threads can hold a shared lock simultaneously.
- Threads holding a 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.
4.2 Exclusive Lock (Write Lock)
- Only one thread can hold an exclusive lock at a time.
- Exclusive lock can only be acquired when no other lock (shared or exclusive) is held on the resource.
- A thread holding an exclusive lock can read and write the resource.
4.3 Compatibility Matrix
| Thread B wants → | Shared Lock | Exclusive Lock |
|---|---|---|
| Thread A holds Shared Lock | ✅ Allowed | ❌ Blocked |
| Thread A holds Exclusive Lock | ❌ Blocked | ❌ Blocked |
| No lock held | ✅ Allowed | ✅ Allowed |
5. ReadWriteLock
5.1 What Is ReadWriteLock?
ReadWriteLock is an interface with two sub-locks:
readLock()— returns aLockthat implements shared lockingwriteLock()— returns aLockthat implements exclusive locking
The standard implementation is ReentrantReadWriteLock.
1ReadWriteLock rwLock = new ReentrantReadWriteLock();2Lock readLock = rwLock.readLock(); // shared lock3Lock writeLock = rwLock.writeLock(); // exclusive lock5.2 When to Use ReadWriteLock
Use when your application has many more reads than writes. Standard synchronized or ReentrantLock makes readers wait for each other even though concurrent reads are perfectly safe. ReadWriteLock allows all readers through simultaneously, only blocking when a write happens.
Ideal scenario: 1000 read operations for every 10 write operations.
5.3 ReadWriteLock Code Example
1import java.util.concurrent.locks.ReadWriteLock;2import java.util.concurrent.locks.ReentrantReadWriteLock;3
4class SharedResource {5
6 // Producer uses a read lock (shared) — multiple threads can read simultaneously7 void produce(ReadWriteLock lock) {8 lock.readLock().lock();9 try {10 System.out.println("Read lock acquired by: " + Thread.currentThread().getName());11 Thread.sleep(8000); // simulate long read12 System.out.println("Read lock released by: " + Thread.currentThread().getName());13 } catch (InterruptedException e) {14 Thread.currentThread().interrupt();15 } finally {16 lock.readLock().unlock();17 }18 }19
20 // Consumer uses a write lock (exclusive) — must wait for all read locks to be released21 void consume(ReadWriteLock lock) {22 lock.writeLock().lock();23 try {24 System.out.println("Write lock acquired by: " + Thread.currentThread().getName());25 Thread.sleep(4000);26 System.out.println("Write lock released by: " + Thread.currentThread().getName());27 } catch (InterruptedException e) {28 Thread.currentThread().interrupt();29 } finally {30 lock.writeLock().unlock();31 }32 }33}34
35public class ReadWriteLockDemo {36 public static void main(String[] args) {37 ReadWriteLock rwLock = new ReentrantReadWriteLock();38 SharedResource r1 = new SharedResource();39 SharedResource r2 = new SharedResource();40 SharedResource r3 = new SharedResource();41
42 Thread t1 = new Thread(() -> r1.produce(rwLock)); // read lock43 Thread t2 = new Thread(() -> r2.produce(rwLock)); // read lock — allowed alongside t144 Thread t3 = new Thread(() -> r3.consume(rwLock)); // write lock — must wait45
46 t1.start();47 t2.start();48 t3.start();49 }50}Read lock acquired by: Thread-0 Read lock acquired by: Thread-1 ← Both readers run simultaneously ✅ [... 8 seconds ...] Read lock released by: Thread-0 Read lock released by: Thread-1 Write lock acquired by: Thread-2 ← Writer waited for both readers to finish [... 4 seconds ...] Write lock released by: Thread-2
5.4 Execution Timeline
produce(), we only acquire a read lock — the code should only read data, not modify it. Acquiring a read lock and then writing data is a semantic violation and can cause race conditions.6. Pessimistic vs Optimistic Locking
6.1 Pessimistic Locking
All locks seen so far — synchronized, ReentrantLock, ReadWriteLock (write lock) — are pessimistic.
Core assumption: "Something WILL go wrong if I don't lock. I'll lock first, do my work, then unlock."
- Prevents conflicts by acquiring a lock before any operation.
- Safe but potentially slow under high concurrency — threads queue up to acquire the lock.
6.2 Optimistic Locking
Core assumption: "Conflicts are RARE. I'll do my work without a lock, but before I commit the result, I'll verify nobody else changed the data while I was working. If they did, I'll retry."
No lock is acquired. Instead, a version number (or timestamp/stamp) is used to detect conflicts.
6.3 How Optimistic Locking Works Database Row Example
Consider a database table:
| ID | Name | Type | Row Version |
|---|---|---|---|
| 123 | Ram | Student | 1 |
| 456 | SJ | Student | 1 |
Scenario: Thread 1 and Thread 2 both read row 123 simultaneously.
1Time T1: Thread 1 reads row 123 → saves row_version = 12Time T1: Thread 2 reads row 123 → saves row_version = 13
4Time T2: Thread 1 computes: change Type to "Teacher"5Time T2: Thread 2 computes: change Type to "X-Student"6
7Time T3: Thread 2 updates first:8 UPDATE table SET type = 'X-Student' WHERE id = 123 AND row_version = 19 → row_version was 1 ✅ → UPDATE SUCCEEDS → row_version auto-incremented to 210
11Time T4: Thread 1 tries to update:12 UPDATE table SET type = 'Teacher' WHERE id = 123 AND row_version = 113 → row_version is now 2 ❌ → UPDATE FAILS → Thread 1 must retry14
15Thread 1 retries:16 Re-reads row 123 → row_version = 217 Re-computes change18 UPDATE table SET type = 'Teacher' WHERE id = 123 AND row_version = 219 → row_version was 2 ✅ → UPDATE SUCCEEDSKey insight: No lock is ever held. Conflicts are detected at commit time using the version number.
7. StampedLock
7.1 What Is StampedLock?
StampedLock (Java 8+) combines two capabilities:
- Read/Write Lock — same shared/exclusive semantics as
ReadWriteLock - Optimistic Read — allows reading without any lock, with a validation step
It is generally faster than ReentrantReadWriteLock because optimistic reads involve no actual locking.
7.2 The Stamp
Every StampedLock locking operation returns a stamp (a long value). This stamp represents the lock state at the time it was acquired. You must pass this stamp back when unlocking or validating.
1StampedLock lock = new StampedLock();2
3long stamp = lock.readLock(); // acquire read lock → returns stamp4try {5 // read data6} finally {7 lock.unlockRead(stamp); // must pass the stamp back8}The stamp is also used by optimistic reads to validate whether the lock state changed (i.e., whether a write happened since the read).
7.3 StampedLock Read/Write Lock Functionality
1import java.util.concurrent.locks.StampedLock;2
3class SharedResource {4
5 // Read lock (shared)6 void produce(StampedLock lock) {7 long stamp = lock.readLock();8 try {9 System.out.println("Read lock acquired by: " + Thread.currentThread().getName());10 Thread.sleep(6000);11 System.out.println("Read lock released by: " + Thread.currentThread().getName());12 } catch (InterruptedException e) {13 Thread.currentThread().interrupt();14 } finally {15 lock.unlockRead(stamp); // must pass the stamp16 }17 }18
19 // Write lock (exclusive)20 void consume(StampedLock lock) {21 long stamp = lock.writeLock();22 try {23 System.out.println("Write lock acquired by: " + Thread.currentThread().getName());24 Thread.sleep(4000);25 System.out.println("Write lock released by: " + Thread.currentThread().getName());26 } catch (InterruptedException e) {27 Thread.currentThread().interrupt();28 } finally {29 lock.unlockWrite(stamp);30 }31 }32}Behavior is identical to ReadWriteLock — multiple readers can hold the read lock simultaneously; the write lock is exclusive.
7.4 StampedLock Optimistic Read
1class SharedResource {2 private int value = 10;3 private final StampedLock lock = new StampedLock();4
5 void optimisticProducer() throws InterruptedException {6 // Step 1: Try an optimistic read — NO actual lock acquired7 long stamp = lock.tryOptimisticRead();8 System.out.println("Took optimistic read. stamp = " + stamp);9
10 // Step 2: Read current value (no lock — just reading)11 int localValue = value;12 System.out.println("Read value: " + localValue + ". Changing to: " + (localValue + 1));13
14 // Step 3: Simulate work delay — during this, another thread might write15 Thread.sleep(6000);16
17 // Step 4: Validate — did any write happen since tryOptimisticRead()?18 if (lock.validate(stamp)) {19 // No write occurred — safe to commit our change20 value = localValue + 1;21 System.out.println("Validation SUCCESS. Value updated to: " + value);22 } else {23 // A write happened while we were working — our data is stale — rollback24 System.out.println("Validation FAILED. Rolling back. value stays: " + value);25 }26 }27
28 void writeConsumer() {29 long stamp = lock.writeLock();30 try {31 System.out.println("Write lock acquired by: " + Thread.currentThread().getName());32 // performs some write operation33 System.out.println("Write lock released by: " + Thread.currentThread().getName());34 } finally {35 lock.unlockWrite(stamp); // incrementing stamp internally36 }37 }38}39
40public class StampedLockDemo {41 public static void main(String[] args) {42 SharedResource resource = new SharedResource();43
44 Thread producer = new Thread(() -> {45 try { resource.optimisticProducer(); }46 catch (InterruptedException e) { Thread.currentThread().interrupt(); }47 });48
49 Thread consumer = new Thread(() -> resource.writeConsumer());50
51 producer.start();52 consumer.start();53 }54}Took optimistic read. stamp = 256 Read value: 10. Changing to: 11 Write lock acquired by: Thread-1 Write lock released by: Thread-1 Validation FAILED. Rolling back. value stays: 10
Output (no write during optimistic read window):
1Took optimistic read. stamp = 2562Read value: 10. Changing to: 113Validation SUCCESS. Value updated to: 117.5 How `validate()` Works Internally
When writeLock() is acquired and unlockWrite() is called, StampedLock increments an internal version counter (the stamp value changes). validate(stamp) checks whether the current internal version still matches the stamp taken at tryOptimisticRead() time. If they differ, a write occurred — validation fails.
This is exactly the same concept as the database row version approach from Section 6.3.
7.6 StampedLock Limitations
StampedLock is NOT reentrant. If the same thread tries to acquire a write lock it already holds, it will deadlock. Use ReentrantReadWriteLock if reentrancy is needed.StampedLock does not support Condition objects (explained in Section 9). For inter-thread communication, use ReentrantLock with Condition instead.8. Semaphore
8.1 What Is a Semaphore?
A Semaphore maintains a set of permits. Each acquire() call takes one permit; each release() returns one permit. If no permits are available, acquire() blocks until one is released.
The key difference from all previous locks: more than one thread can be inside the critical section simultaneously — you control exactly how many.
1Semaphore semaphore = new Semaphore(N); // N = max simultaneous threads allowed8.2 Key Methods
| Method | Description |
|---|---|
acquire() | Acquires one permit. Blocks if none available. |
acquire(int n) | Acquires n permits. |
release() | Releases one permit. |
release(int n) | Releases n permits. |
tryAcquire() | Tries to acquire without blocking. Returns true/false. |
availablePermits() | Returns the number of currently available permits. |
8.3 Code Example Semaphore with 2 Permits
1import java.util.concurrent.Semaphore;2
3class SharedResource {4
5 void produce(Semaphore semaphore) {6 try {7 semaphore.acquire(); // take one permit — blocks if 0 available8 System.out.println("Lock acquired by: " + Thread.currentThread().getName());9 Thread.sleep(4000);10 System.out.println("Lock released by: " + Thread.currentThread().getName());11 } catch (InterruptedException e) {12 Thread.currentThread().interrupt();13 } finally {14 semaphore.release(); // always return the permit15 }16 }17}18
19public class SemaphoreDemo {20 public static void main(String[] args) {21 Semaphore semaphore = new Semaphore(2); // ONLY 2 threads allowed simultaneously22
23 SharedResource resource = new SharedResource();24
25 Thread t1 = new Thread(() -> resource.produce(semaphore), "Thread-0");26 Thread t2 = new Thread(() -> resource.produce(semaphore), "Thread-1");27 Thread t3 = new Thread(() -> resource.produce(semaphore), "Thread-2");28 Thread t4 = new Thread(() -> resource.produce(semaphore), "Thread-3");29
30 t1.start();31 t2.start();32 t3.start();33 t4.start();34 }35}Lock acquired by: Thread-0
Lock acquired by: Thread-1 ← 2 threads inside simultaneously ✅
Thread-2 and Thread-3 are BLOCKED
Lock released by: Thread-0 ← one permit freed
Lock acquired by: Thread-2 ← Thread-2 gets the freed permit
Lock released by: Thread-1 ← another permit freed
Lock acquired by: Thread-3 ← Thread-3 gets the freed permit
Lock released by: Thread-2
Lock released by: Thread-38.4 Semaphore Execution Timeline
8.5 Real-World Use Cases for Semaphore
Connection Pool:
1Database has max 5 connections.2Semaphore(5) → at most 5 threads can hold connections simultaneously.3Thread 6, 7, 8... wait until a connection is returned (released).Printer Queue:
1Office has 2 printers.2Semaphore(2) → at most 2 print jobs run at once.3Others wait in queue.Rate Limiting:
1API allows 10 concurrent requests.2Semaphore(10) → enforces this limit.8.6 Semaphore as a Binary Semaphore (mutex)
A Semaphore(1) behaves like a mutex — only one thread at a time:
1Semaphore mutex = new Semaphore(1); // equivalent to a lockUnlike ReentrantLock, a Semaphore(1) can be released by a different thread than the one that acquired it. This makes it useful for signaling scenarios.
8.7 Fair vs Unfair Semaphore
1Semaphore fairSemaphore = new Semaphore(2, true); // FIFO — prevents starvation2Semaphore unfairSemaphore = new Semaphore(2, false); // default — better throughput9. Inter-Thread Communication with Custom Locks `Condition`
9.1 The Problem
wait() and notify() only work with synchronized (monitor locks). When using ReentrantLock, ReadWriteLock, or StampedLock, you cannot use wait()/notify() — they throw IllegalMonitorStateException.
1ReentrantLock lock = new ReentrantLock();2lock.lock();3try {4 wait(); // ❌ IllegalMonitorStateException — not on a monitor lock!5 notify(); // ❌ same6} finally {7 lock.unlock();8}9.2 The Solution `Condition`
Condition is the custom-lock equivalent of wait()/notify(). It is obtained from a Lock object:
1ReentrantLock lock = new ReentrantLock();2Condition condition = lock.newCondition(); // condition tied to this locksynchronized method | Condition equivalent |
|---|---|
wait() | condition.await() |
notify() | condition.signal() |
notifyAll() | condition.signalAll() |
Rules (same as wait()/notify()):
await()andsignal()must be called while the thread holds the lock.await()releases the lock and puts the thread in WAITING state.signal()/signalAll()wakes up waiting threads.
9.3 Condition Interface Methods
1void await() throws InterruptedException // equivalent to wait()2void awaitUninterruptibly() // await() that ignores interrupts3long awaitNanos(long nanosTimeout) // timed await4boolean await(long time, TimeUnit unit) // timed await5boolean awaitUntil(Date deadline) // await until a specific time6void signal() // equivalent to notify()7void signalAll() // equivalent to notifyAll()9.4 Producer-Consumer with ReentrantLock + Condition
1import java.util.concurrent.locks.Condition;2import java.util.concurrent.locks.ReentrantLock;3
4class SharedResource {5 private boolean itemAvailable = false;6 private final ReentrantLock lock = new ReentrantLock();7 private final Condition condition = lock.newCondition();8
9 void addItem() throws InterruptedException {10 lock.lock();11 try {12 // If item is already available, wait for it to be consumed first13 while (itemAvailable) {14 System.out.println("[Producer] Item already present. Waiting...");15 condition.await(); // releases lock, enters WAITING16 }17 // Produce the item18 itemAvailable = true;19 System.out.println("[Producer] Item added. Signaling consumer...");20 condition.signal(); // wake up the consumer21 } finally {22 lock.unlock();23 }24 }25
26 void consumeItem() throws InterruptedException {27 lock.lock();28 try {29 // If item is not yet available, wait for producer30 while (!itemAvailable) {31 System.out.println("[Consumer] Item not available. Waiting...");32 condition.await(); // releases lock, enters WAITING33 }34 // Consume the item35 itemAvailable = false;36 System.out.println("[Consumer] Item consumed. Signaling producer...");37 condition.signal(); // wake up the producer38 } finally {39 lock.unlock();40 }41 }42}43
44public class ConditionDemo {45 public static void main(String[] args) {46 SharedResource resource = new SharedResource();47
48 Thread producer = new Thread(() -> {49 for (int i = 0; i < 3; i++) {50 try { resource.addItem(); }51 catch (InterruptedException e) { Thread.currentThread().interrupt(); }52 }53 }, "ProducerThread");54
55 Thread consumer = new Thread(() -> {56 for (int i = 0; i < 3; i++) {57 try { resource.consumeItem(); }58 catch (InterruptedException e) { Thread.currentThread().interrupt(); }59 }60 }, "ConsumerThread");61
62 producer.start();63 consumer.start();64 }65}[Consumer] Item not available. Waiting... [Producer] Item added. Signaling consumer... [Consumer] Item consumed. Signaling producer... [Producer] Item added. Signaling consumer... [Consumer] Item consumed. Signaling producer... [Producer] Item added. Signaling consumer... [Consumer] Item consumed. Signaling producer...
9.5 Multiple Conditions on One Lock
A key advantage of Condition over wait()/notifyAll() is that one lock can have multiple condition queues:
1ReentrantLock lock = new ReentrantLock();2Condition notFull = lock.newCondition(); // producer waits here when buffer full3Condition notEmpty = lock.newCondition(); // consumer waits here when buffer empty4
5// Producer:6while (bufferFull) notFull.await();7// ... add item ...8notEmpty.signal(); // wake only consumers, not producers9
10// Consumer:11while (bufferEmpty) notEmpty.await();12// ... consume item ...13notFull.signal(); // wake only producers, not consumersWith notifyAll() on a synchronized block, you'd wake ALL waiting threads (both producers and consumers). With Condition, you can wake only the right category. This improves efficiency significantly.
10. Full Comparison Table
| Feature | synchronized | ReentrantLock | ReadWriteLock | StampedLock | Semaphore |
|---|---|---|---|---|---|
| Lock type | Monitor (per object) | Exclusive | Shared + Exclusive | Shared + Exclusive + Optimistic | Permit-based (N threads) |
| Object independence | ❌ Per-object | ✅ Independent | ✅ Independent | ✅ Independent | ✅ Independent |
| Reentrant | ✅ | ✅ | ✅ | ❌ | ❌ |
| Multiple readers | ❌ | ❌ | ✅ | ✅ | ✅ (N permits) |
| Optimistic read | ❌ | ❌ | ❌ | ✅ | ❌ |
| tryLock / non-blocking | ❌ | ✅ | ✅ | ✅ | ✅ |
| Fair ordering | ❌ | ✅ (optional) | ✅ (optional) | ❌ | ✅ (optional) |
| Inter-thread comm | wait/notify | Condition.await/signal | Condition.await/signal | ❌ Not supported | ❌ Not supported |
| Must unlock in finally | ❌ (auto) | ✅ | ✅ | ✅ | ✅ |
| Best use case | Simple mutual exclusion, same object | Multi-object mutual exclusion | Read-heavy | Very high read throughput | Throttle N concurrent threads |
11. Common Mistakes
Mistake 1: Forgetting `unlock()` in `finally`
1lock.lock();2doWork(); // if this throws → unlock() never called → deadlock!3lock.unlock();Fix:
1lock.lock();2try {3 doWork();4} finally {5 lock.unlock(); // guaranteed to run6}Mistake 2: Using `wait()`/`notify()` with Custom Locks
1ReentrantLock lock = new ReentrantLock();2lock.lock();3try {4 wait(); // ❌ IllegalMonitorStateException5} finally {6 lock.unlock();7}Fix: Use Condition:
1Condition condition = lock.newCondition();2lock.lock();3try {4 condition.await(); // ✅5} finally {6 lock.unlock();7}Mistake 3: Calling `StampedLock` Reentrantly
1StampedLock lock = new StampedLock();2long s1 = lock.writeLock();3long s2 = lock.writeLock(); // ❌ DEADLOCK — StampedLock is not reentrantFix: Use ReentrantReadWriteLock if reentrancy is needed.
Mistake 4: Trusting `tryOptimisticRead()` Without `validate()`
1long stamp = lock.tryOptimisticRead();2int value = sharedValue; // read without lock3// ... forgot to validate! ...4use(value); // ❌ may use stale data if a write happenedFix: Always validate before using optimistically read data:
1long stamp = lock.tryOptimisticRead();2int value = sharedValue;3if (!lock.validate(stamp)) {4 // re-read with a proper read lock5 stamp = lock.readLock();6 try { value = sharedValue; }7 finally { lock.unlockRead(stamp); }8}9use(value); // ✅ safeMistake 5: Writing Inside a Read Lock
1lock.readLock().lock();2try {3 sharedValue = 42; // ❌ modifying during shared lock — other readers see partial state4} finally {5 lock.readLock().unlock();6}Fix: Use write lock for any modification.
Mistake 6: Not Releasing Semaphore Permits in `finally`
1semaphore.acquire();2doWork(); // exception thrown → release() never called → permits leak3semaphore.release();Fix:
1semaphore.acquire();2try {3 doWork();4} finally {5 semaphore.release(); // always returns the permit6}12. Best Practices
- Always unlock in
finallyfor all custom locks — it's the most important rule.
- Use the simplest lock that solves your problem:
- Same-object mutual exclusion →
synchronized - Cross-object mutual exclusion →
ReentrantLock - Read-heavy workload →
ReadWriteLockorStampedLock - Throttle concurrent access →
Semaphore
- Use
whileloop withcondition.await()just like withwait()— to guard against spurious wakeups:
1 while (!condition) {2 cond.await();3 }- Prefer
signalAll()oversignal()unless you are certain which thread to wake.
- Use multiple
Conditionobjects to avoid waking the wrong category of threads.
- Validate after every
tryOptimisticRead()— never skip this step.
- Never call
StampedLockreentrantly — it will deadlock.
- Consider
java.util.concurrenthigher-level tools (BlockingQueue,CountDownLatch,CyclicBarrier,Exchanger) before reaching for raw locks — they are safer and clearer.
- Name your threads and add logging around lock acquisition and release — makes debugging far easier.
13. Interview Notes
Q1: What is the difference between synchronized and ReentrantLock?
synchronized puts a monitor lock on a specific object — different objects get different locks. ReentrantLock is an independent lock object — any thread with a reference to the same instance competes for it regardless of which target object they're calling. ReentrantLock also supports tryLock(), lockInterruptibly(), fair ordering, and Condition for inter-thread communication.
Q2: What is the difference between shared lock and exclusive lock?
A shared lock (read lock) allows multiple threads to hold it simultaneously — used for read-only access. An exclusive lock (write lock) allows only one thread to hold it — used when data is being modified. If any shared lock is held, no exclusive lock can be acquired; if an exclusive lock is held, no other lock of any kind can be acquired.
Q3: When would you use ReadWriteLock?
When the application has significantly more reads than writes. Multiple reader threads can proceed concurrently since reading doesn't corrupt data. Writers still get exclusive access. A typical scenario is a cache, configuration store, or any read-heavy data structure.
Q4: What is optimistic locking? How is it different from pessimistic locking?
Pessimistic locking acquires a lock before any operation, preventing conflicts. Optimistic locking assumes conflicts are rare — it reads data without a lock, performs work, then validates at commit time whether the data changed (using a version number or stamp). If validation fails, it rolls back and retries. It performs better under low contention but wastes work under high contention.
Q5: How does StampedLock implement optimistic locking in Java?
tryOptimisticRead() returns a stamp (a version number) without acquiring any lock. After reading/computing, validate(stamp) checks whether any writeLock() was acquired and released since the stamp was taken. If yes, the stamp is invalidated (a write changed the version), and the thread must re-read with a proper lock. This mirrors database row-version optimistic concurrency control.
Q6: How does Semaphore differ from ReentrantLock?
ReentrantLock allows only one thread at a time (binary mutex). Semaphore(N) allows up to N threads simultaneously. Semaphore is not reentrant and a permit can be released by a different thread than the one that acquired it (unlike ReentrantLock).
Q7: Why can't wait() and notify() be used with custom locks like ReentrantLock?
wait() and notify() are tied to the monitor lock of an object (the one acquired by synchronized). Custom locks use their own internal state — they don't use the monitor. So wait() would throw IllegalMonitorStateException because the thread doesn't hold a monitor lock. The equivalent is Condition.await() and Condition.signal(), obtained via lock.newCondition().
Q8: What is the advantage of Condition over notifyAll()?
With notifyAll() on a synchronized block, all waiting threads are woken — both producers and consumers — causing unnecessary context switching. With Condition, one lock can have multiple condition queues. You can create notFull and notEmpty conditions and signal only producers or only consumers, improving efficiency.
Q9: Is StampedLock reentrant?
No. If a thread holding a StampedLock write lock tries to acquire it again, it will deadlock. Use ReentrantReadWriteLock if reentrancy is required.
Q10: In which real scenarios would you use a Semaphore?
Connection pools (limit N concurrent DB connections), thread pools (limit active workers), API rate limiting (max N concurrent requests), printer queues (N physical printers), or any scenario where a fixed-capacity shared resource must be accessed by limited concurrent threads.
14. Practice Questions
Easy
- Create a
ReentrantLockexample where three threads call the same method on different objects but the lock ensures they run one at a time.
- Demonstrate
lock.tryLock()— have a thread print "lock busy, doing alternate work" if the lock isn't immediately available.
- Create a
Semaphore(3)and start 6 threads. Show that only 3 run at a time.
- Write a
ReadWriteLockexample where 3 reader threads run simultaneously but a writer thread must wait.
- Demonstrate that calling
wait()inside aReentrantLockblock throwsIllegalMonitorStateException.
Medium
- Implement producer-consumer using
ReentrantLock+Condition(single item, matching the lecture example). Verify the producer waits when item is already available.
- Implement a fair
ReentrantLockand demonstrate that threads acquire the lock in FIFO order.
- Create a
ReadWriteLockcache where multiple threads read cached values concurrently, but a write invalidates and refreshes the cache with exclusive access.
- Write a thread-safe connection pool using
Semaphorethat tracks available and in-use connections.
- Implement producer-consumer with two
Conditionobjects (notFull,notEmpty) on oneReentrantLock. Verify producers only signal consumers and vice versa.
Hard
- Implement the
StampedLockoptimistic read example: one thread reads and computes, another thread performs a write during the computation window. Verify rollback occurs. Then run without the writer — verify success.
- Implement a bounded blocking queue (
put()blocks when full,take()blocks when empty) usingReentrantLockand twoConditionobjects.
- Show a deadlock with two
ReentrantLockobjects (Thread 1 holds Lock A, waits for Lock B; Thread 2 holds Lock B, waits for Lock A). Then fix it using consistent lock ordering.
- Build a read-heavy counter class using
StampedLockwith optimistic reads forget()and a write lock forincrement(). Compare throughput against asynchronizedversion under a 100:1 read-to-write ratio.
- Explain and demonstrate the difference between
Semaphore.release()being called by a different thread than the one that calledacquire(). Why is this possible withSemaphorebut notReentrantLock?
15. Summary
Revision Bullets:
synchronizedputs monitor lock per object — doesn't work when different objects need to share a critical section.ReentrantLockis object-independent — same lock instance enforces mutual exclusion across any number of objects.- Always call
unlock()in afinallyblock for all custom locks. - Shared lock (read lock) = multiple threads can hold simultaneously, read only. Exclusive lock (write lock) = one thread only, read/write.
ReadWriteLock= multiple concurrent readers OR one exclusive writer. Best for read-heavy workloads.- Pessimistic locking = lock first, do work, unlock. Optimistic locking = do work without lock, validate version at commit, rollback if version changed.
StampedLocksupports read/write locks plus optimistic reads viatryOptimisticRead()+validate(). Not reentrant.Semaphore(N)allows exactly N threads inside the critical section simultaneously. Use for connection pools, rate limiting, resource throttling.wait()/notify()do not work with custom locks. UseConditioninstead:condition.await()=wait(),condition.signal()=notify(),condition.signalAll()=notifyAll().- A single
ReentrantLockcan have multipleConditionobjects, allowing precise signaling (only wake producers, or only wake consumers). - Always use
whileloops withawait(), neverif, to guard against spurious wakeups.
Mastery check
How well can you recall this?
Finished this lesson?