Commit 3d80046
committed
feat: Implement fair ReentrantLock to ensure equal thread access
WHAT the code does:
- Defines FairLock class using java.util.concurrent.locks.ReentrantLock.
- Creates a lock (lock1) with fairness policy enabled (`new ReentrantLock(true)`).
- Ensures threads acquire the lock in order, preventing starvation.
- accessResource():
- Acquires lock with lock1.lock().
- Simulates work by sleeping for 1 second.
- Uses try–finally to guarantee lock release (lock1.unlock()).
- Prints messages when lock is acquired and released.
- main():
- Creates a FairLock instance.
- Defines a task (Runnable) to call accessResource().
- Starts three threads (Thread 1, Thread 2, Thread 3) with staggered start times.
- Demonstrates fairness: threads acquire the lock in the order they requested it.
WHY this matters:
- Shows correct usage of ReentrantLock with fairness parameter.
- Demonstrates how to avoid thread starvation, ensuring all threads eventually get access.
- Highlights best practice: always release locks in a finally block.
- Illustrates real-world concurrency control beyond synchronized blocks.
HOW it works:
1. Thread 1 starts and acquires the lock.
2. While Thread 1 is holding the lock, Thread 2 and Thread 3 queue up.
3. Because fairness = true, threads acquire lock in FIFO order:
- Thread 2 next, then Thread 3.
4. Each thread prints acquired/released messages around its 1-second simulated work.
Tips and gotchas:
- Fair locks prevent starvation but may have lower throughput than unfair locks due to stricter scheduling.
- Always use try–finally to ensure unlock() executes even if exceptions occur.
- Avoid holding locks for long periods (sleep is for demonstration only).
- For most use-cases, synchronized or default (non-fair) ReentrantLock is sufficient; fairness is useful in long-lived contention scenarios.
Use-cases / analogies:
- Ticket booking system where all customers must be served fairly.
- Print spoolers ensuring jobs are processed in the order submitted.
- Shared banking resource (e.g., account transfers) requiring strict fairness in processing.
Short key: java concurrency reentrant lock fairness starvation-prevention.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 9b395d9 commit 3d80046
1 file changed
+5
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2 | 2 | | |
3 | 3 | | |
4 | 4 | | |
5 | | - | |
6 | | - | |
| 5 | + | |
| 6 | + | |
7 | 7 | | |
8 | 8 | | |
9 | | - | |
| 9 | + | |
10 | 10 | | |
11 | 11 | | |
12 | | - | |
| 12 | + | |
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
| |||
38 | 38 | | |
39 | 39 | | |
40 | 40 | | |
41 | | - | |
| 41 | + | |
0 commit comments