Acquiring and Releasing the Lock
You'll learn: How synchronized methods automatically manage lock acquisition and release, even when exceptions occur.
When a thread enters a synchronized method, it acquires the object's intrinsic lock (monitor). This is automatic—you don't call a method to grab the lock; the synchronized keyword handles it. Once the thread holds the lock, no other thread can enter any synchronized method on that same object until the lock is released.
The lock is released automatically when:
- The thread exits the method normally (by reaching the end or returning)
- The thread exits the method by throwing an exception
This automatic release mechanism is crucial. Even if your synchronized method crashes with a NullPointerException or any other exception, the lock is still released. This prevents deadlock scenarios where a lock could be held forever by a failed thread.
Why Automatic Release Matters
Think of the lock like a restroom key. When you enter (acquire), you lock the door. Whether you finish normally or have to leave suddenly due to an emergency (exception), you always return the key when you exit. The system guarantees no one gets locked in permanently.
public synchronized void increment() {
// Lock acquired automatically here
count++;
// Lock released automatically here
} // ← Lock released even if an exception occurs above
You cannot manually release the lock early or hold it longer—the method's execution scope defines the lock's lifetime. This simplicity prevents many programmer errors but also means you need to keep synchronized methods short and efficient.
Key Takeaway:
A synchronized method acquires the object's lock on entry and always releases it on exit—whether the method completes normally or throws an exception—ensuring no lock is ever orphaned.