Only One Thread Executes at a Time
What you'll learn: You'll understand how synchronized instance methods ensure that only one thread can execute them on the same object at any given moment.
When you mark an instance method with synchronized, Java enforces mutual exclusion: at most one thread can execute any synchronized instance method on the same object simultaneously.
This is the core protection mechanism against race conditions. Even if two threads call different synchronized methods on the same object, only one can proceed—the other must wait for the lock to be released.
How It Works
Think of it like a single bathroom key in an office. The object is the bathroom, and each synchronized method is a different action you might do inside (washing hands, using the mirror). The key (the monitor lock) ensures only one person can be in the bathroom at a time, regardless of what they're doing inside.
When a thread calls a synchronized instance method:
- It attempts to acquire the object's intrinsic lock
- If another thread already holds that lock, the calling thread blocks (enters BLOCKED state)
- Once the lock is acquired, the thread executes the method body
- When the method completes (normally or via exception), the lock is automatically released
Example with Multiple Synchronized Methods
public class BankAccount {
private int balance = 0;
public synchronized void deposit(int amount) {
balance += amount; // Only one thread here at a time
}
public synchronized void withdraw(int amount) {
balance -= amount; // Only one thread here at a time
}
}
If Thread A is executing deposit() and Thread B calls withdraw() on the same BankAccount object, Thread B must wait—even though they're different methods.
Key Takeaway: Synchronized instance methods on the same object are mutually exclusive; the object's lock can be held by only one thread at a time, preventing concurrent access to all synchronized methods.