🤔 What is Starvation?
Starvation happens when a thread waits forever because other threads are constantly taking the lock before it can.
In the context of ReadWriteLock, the writer thread can starve if readers keep coming in back-to-back.
📘 How ReadWriteLock Works by Default
- Readers can come in as long as no writer is active or waiting.
- If a writer is waiting, but readers keep coming, the writer may be postponed indefinitely.
🔁 Starvation in Action
Imagine this:
ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // Non-fair mode
- Thread A wants to write → waits to acquire the write lock.
- Meanwhile:
- Thread B comes and reads.
- Thread C comes and reads.
- Thread D comes and reads.
- And this keeps happening…
🔁 Because read locks are allowed concurrently, they keep sneaking in before the writer gets a chance.
📛 The writer never gets the lock — it’s starved.
✅ Solution: Use Fair Mode
ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true); // fair mode
In fair mode:
- Threads acquire locks in order of arrival (FIFO).
- If a writer is waiting, new readers must wait too, giving the writer a chance.
📌 Summary
| Behavior | Non-Fair Mode (default) | Fair Mode (true) |
|---|---|---|
| Readers can “cut in line”? | ✅ Yes | ❌ No |
| Writers may starve? | ✅ Possible | ❌ Less likely |
| Performance | 🔼 Faster | 🔽 Slightly slower |