Commit 5143320
committed
feat(concurrency): demonstrate reentrant behavior using ReentrantLock with nested method calls
WHAT:
- Added `ReentrantExample2` class using a `ReentrantLock` to showcase **reentrancy**.
- Implemented `outerMethod()` which locks, prints, and calls `innerMethod()`.
- Implemented `innerMethod()` which locks again, proving that the same thread can acquire the lock multiple times.
- Main creates an instance and calls `outerMethod()` to demonstrate the flow.
WHY:
- In real systems, methods often call other synchronized methods on the same object.
- Without **reentrancy**, such nested calls would deadlock because the thread already holds the lock.
- Reentrant locks maintain a **hold count** → the same thread can re-acquire the lock safely, but must unlock the same number of times.
HOW IT WORKS:
1. Thread acquires lock in `outerMethod()`.
2. Calls `innerMethod()`, which **again acquires the same lock**.
3. ReentrantLock allows it since the caller thread already owns the lock.
4. Both `outerMethod` and `innerMethod` print messages.
5. Locks are released in LIFO order via `finally` blocks.
OUTPUT (example):
Outer Method
Inner Method
BENEFITS & USE CASES:
- ✅ Prevents deadlocks when methods call each other recursively.
- ✅ Allows fine-grained locking with advanced features (`tryLock`, `lockInterruptibly`).
- ✅ Useful in libraries, frameworks, and systems where nested monitor locks are common.
KEY TAKEAWAYS (Interview-Ready):
- `ReentrantLock` works like `synchronized` but with more control (timeouts, fairness).
- Same thread can lock multiple times → must unlock equal times.
- Always release locks in `finally` to avoid resource leaks.
- Example: in a banking system, `withdraw()` might internally call `checkBalance()` → both can safely share the same lock.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 534b6d1 commit 5143320
File tree
1 file changed
+12
-8
lines changed- Section19MultiThreading/Locks/src/Lock
1 file changed
+12
-8
lines changedLines changed: 12 additions & 8 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | 3 | | |
4 | | - | |
5 | | - | |
6 | | - | |
7 | | - | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
8 | 9 | | |
9 | 10 | | |
10 | 11 | | |
| |||
17 | 18 | | |
18 | 19 | | |
19 | 20 | | |
20 | | - | |
| 21 | + | |
21 | 22 | | |
22 | 23 | | |
23 | 24 | | |
| |||
30 | 31 | | |
31 | 32 | | |
32 | 33 | | |
33 | | - | |
| 34 | + | |
34 | 35 | | |
35 | 36 | | |
36 | 37 | | |
37 | | - | |
38 | | - | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
0 commit comments