Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Concurrency

    synchronized

    Every Java object has a built-in lock called its monitor (or intrinsic lock).

    Chapter 3 of 123 min read

    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 synchronized block 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 synchronized method locks this (or, for a static method, the class object):

      Java
      static synchronized void inc() {
          syncCount++;
      }
    • synchronized locks 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:

    Output
    synchronized count = 1000000

    Always 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:

    1. Mutual exclusion: only one thread runs the block at a time (for the same lock object).

    2. 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 on this or 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 questions
    1

    What does a synchronized method lock on? A static synchronized one?

    Show answer

    The instance (this); the class object.

    2

    Name the two guarantees of synchronized.

    Show answer

    Mutual exclusion and visibility (happens-before between release and acquire).

    3

    What does "reentrant" mean?

    Show answer

    A thread holding a lock can acquire it again without blocking itself.

    4

    Why lock on a private object rather than this?

    Show answer

    Outside code could also lock on this, interfering (causing contention or deadlock); a private lock is under your control only.