Multiple Synchronized Methods on the Same Object
What you'll learn: How all synchronized instance methods on the same object share a single lock, preventing any of them from running concurrently.
The Shared Lock Principle
You now know that marking a method as synchronized makes a thread acquire the object's intrinsic lock before executing. Here's the crucial detail: an object has only ONE monitor lock, and ALL synchronized instance methods compete for that same lock.
This means if thread A is executing any synchronized method on an object, thread B cannot execute any other synchronized method on that same object—even if those methods touch completely different fields.
Why This Matters
public class BankAccount {
private int balance;
private String accountHolder;
public synchronized void deposit(int amount) {
balance += amount;
// Thread holds the lock here
}
public synchronized void updateName(String name) {
accountHolder = name;
// Same lock as deposit()!
}
}
If thread 1 calls deposit() on an account instance, thread 2 calling updateName() on that same account must wait—even though balance and accountHolder are unrelated fields. Both methods share the one lock belonging to account.
Think of It Like This
Imagine a house (the object) with multiple rooms (methods). There's only one front-door key (the lock). When someone enters any room using that key, nobody else can enter any room until the key is returned.
Key Takeaway: All synchronized instance methods on the same object share one intrinsic lock, ensuring mutually exclusive access across all synchronized operations on that instance—not just within individual methods.