Synchronized Blocks and Methods
What you'll learn: How to use synchronized constructs in Java to protect critical sections and ensure only one thread executes them at a time.
The Core Idea
In multi-threaded programs, we've learned that critical sections are code regions where shared data gets modified. Without protection, multiple threads accessing these sections simultaneously cause race conditions. Java's synchronized keyword provides mutual exclusion—guaranteeing only one thread can execute a protected section at a time.
Think of it like a single-occupancy bathroom with a lock. When someone enters and locks the door (acquires the lock), everyone else must wait outside. When they leave and unlock it (release the lock), the next person can enter.
Synchronized Methods
Mark an entire method with synchronized:
public synchronized void increment() {
counter++; // Critical section protected
}
This locks on the object instance (this). Only one thread can execute this method on that object at any moment.
Synchronized Blocks
For finer control, synchronize just part of a method:
public void updateBalance(int amount) {
// Non-critical work here
synchronized(this) {
balance += amount; // Only this needs protection
}
// More non-critical work
}
You can lock on any object:
private final Object lock = new Object();
public void safeDivide() {
synchronized(lock) {
result = numerator / denominator;
}
}
Why It Matters
Synchronized constructs make atomic operations possible at a higher level than simple variables. They bundle multiple statements into one uninterruptible unit, preventing data corruption when multiple threads modify shared state.
Key Takeaway: Synchronized methods and blocks enforce mutual exclusion by allowing only one thread at a time to execute protected code, preventing race conditions in critical sections.