The Plain Picture#
Every room in the office has one key hanging by the door. To work in a room, you take its key; anyone else who wants that room waits by the door until you hang the key back.
The Real Names#
Every Java object has a built-in lock called its monitor (or intrinsic lock).
A
synchronizedblock takes that lock on entry and releases it on exit — even if an exception is thrown:Java synchronized (lockObject) { // only one thread at a time, per lockObject count++; }A
synchronizedmethod locksthis(or, for astaticmethod, the class object):Java static synchronized void inc() { syncCount++; }synchronizedlocks are reentrant: a thread that already holds a lock can take it again (e.g. a synchronized method calling another synchronized method on the same object) without deadlocking itself.
Under the Hood#
Four threads each incrementing 250,000 times through a synchronized method:
synchronized count = 1000000Always exactly right — unlike the unsafe version in Operating Systems Ch 8, which lost hundreds of thousands of updates.
synchronized guarantees two things — interviewers want both:
Mutual exclusion: only one thread runs the block at a time (for the same lock object).
Visibility: everything a thread wrote before releasing the lock is visible to the next thread that acquires it. Why this second guarantee is needed at all is the next chapter.
Choosing the lock object:
Lock on a private final object (
private final Object lock = new Object();), not onthisor a public object, so outside code can't interfere with your locking.All code touching the shared data must use the same lock. Two different lock objects protect nothing.
Keep synchronized blocks short; never make network calls while holding a lock.
Check yourself
4 questionsWhat does a synchronized method lock on? A static synchronized one?
Show answerHide answer
The instance (this); the class object.
Name the two guarantees of synchronized.
Show answerHide answer
Mutual exclusion and visibility (happens-before between release and acquire).
What does "reentrant" mean?
Show answerHide answer
A thread holding a lock can acquire it again without blocking itself.
Why lock on a private object rather than this?
Show answerHide answer
Outside code could also lock on this, interfering (causing contention or deadlock); a private lock is under your control only.