🚀 Master Concurrency & Multithreading in Java!
Subscribe to Ram N Java for clean, visual, and beginner-friendly programming tutorials!
🔔 Subscribe NowWhat is the Lock Design Pattern?
In multithreaded systems, when multiple threads access and mutate shared resources concurrently, data corruption and race conditions can easily occur. The Lock Design Pattern provides an essential synchronization mechanism to safeguard shared data.
Core Definition: The Lock Pattern ensures that one thread puts a lock on a shared resource, preventing other threads from accessing or modifying it until the operation is completed.
The Problem: Shared Bank Account Without a Lock
Consider a joint bank account shared between two people, John (Thread A) and Tina (Thread B). The account has a balance of ₹1,000. Both attempt to withdraw ₹1,000 at the same moment:
- Thread A (John): Calls the withdraw method for ₹1,000. It passes the precondition check (₹1,000 ≥ ₹1,000). Before deducting the balance, Thread A is suspended or sleeps.
- Thread B (Tina): Enters the method concurrently. Because the balance hasn't been updated yet, it still reads ₹1,000. It validates successfully, deducts ₹1,000, sets the balance to ₹0, and withdraws the money.
- Thread A Resumes: Now Thread A wakes up past the validation step and executes the deduction:
0 - 1000 = -1000, allowing John to withdraw ₹1,000 as well!
Although only ₹1,000 was available in the account, a total of ₹2,000 was withdrawn, leaving the balance corrupted at −₹1,000.
The Solution: Applying the Lock Pattern
To resolve this race condition, we enforce mutual exclusion by placing a lock on the withdraw operation:
public class BankAccount {
private int balance = 1000;
// Synchronized lock ensures mutual exclusion
public synchronized void withdraw(int amount) {
if (amount > 0 && balance >= amount) {
System.out.println(Thread.currentThread().getName() + " is withdrawing: " + amount);
balance -= amount;
System.out.println("Remaining balance: " + balance);
} else {
System.out.println("Insufficient funds for: " + Thread.currentThread().getName());
}
}
}
How the Lock Mechanism Protects Data
- When Thread A enters the method, it acquires the lock on the bank account resource.
- If Thread B tries to enter, it is blocked because the lock is held. Thread B must wait until Thread A finishes.
- Thread A completes the withdrawal, reduces the balance to ₹0, and releases the lock.
- Thread B enters, re-evaluates the balance, finds insufficient funds (₹0 < ₹1,000), and is rejected safely without causing data inconsistency.
Key Advantages of the Lock Pattern
- Guarantees Thread Safety: Prevents multiple threads from simultaneously mutating shared variables.
- Eliminates Race Conditions: Ensures atomic execution for critical sections of code.
- Flexible Implementations: Can be achieved via intrinsic locks (
synchronizedblocks/methods) or explicit locks (java.util.concurrent.locks.ReentrantLock).
Recommended Concurrency & Design Pattern Tutorials:
Click here to watch in Youtube : https://www.youtube.com/watch?v=qTwq10Mj5DU
| Lock Design Pattern |
See also:
No comments:
Post a Comment