Choosing the Lock Object
You'll learn how to select the best object to synchronize on—whether this, a class object, or a dedicated lock—to control concurrent access effectively.
The Core Decision
When you write a synchronized block, you must choose which object's lock to acquire. This isn't just syntax—it's a design decision that affects correctness, granularity, and visibility of your synchronization.
synchronized(lockObject) {
// critical section
}
The lockObject can be:
1. this (The Current Instance)
Synchronize on the object itself. Fine-grained when protecting instance state:
synchronized(this) {
this.balance += amount;
}
Caveat: External code can also synchronize on this, potentially causing unintended contention or deadlock.
2. The Class Object (ClassName.class)
For protecting static state shared across all instances:
synchronized(BankAccount.class) {
totalAccounts++;
}
3. A Dedicated Private Lock Object
The safest pattern—prevents external interference:
private final Object lock = new Object();
public void deposit(int amount) {
synchronized(lock) {
balance += amount;
}
}
No outside code can accidentally lock on your lock object because it's private.
Which Should You Choose?
- Use
thiswhen simplicity matters and you control all synchronization - Use
Class.classfor static data protection - Use a dedicated lock when you need isolation, multiple locks for different purposes, or when building libraries
Key Takeaway: Choose your lock object deliberately—this is convenient but exposed, while a private dedicated lock object provides the strongest encapsulation and prevents external interference with your synchronization strategy.