Stop 12 · Multithreading & JVM InternalsTopics · 2/9

Synchronization & Locks

Part of the Java Roadmap

In short

When two threads change the same variable, updates quietly go missing. Locks make threads take turns on shared data so the numbers stay correct.

When threads share data, race conditions can corrupt it. synchronized blocks, ReentrantLock and atomic classes like AtomicInteger make access safe. Badly ordered locks can cause deadlocks.

The jaadu holds a single big brass key outside a small door while a short queue of colleagues waits patiently behind it in an office corridor.

Think of it like this

The single bathroom key

A small office in Indore has one bathroom and one key hanging by the door. Whoever takes the key goes in, and everyone else waits until it is back on the hook. synchronized is that key: only one thread at a time can be inside the protected block for the same object.

Watch it happen

Two ways to guard a counter

synchronized

  • Built into the language
  • Lock released automatically, even on exceptions
  • Simple and enough for most code

ReentrantLock

  • lock() and unlock() called by you
  • Supports tryLock with a timeout
  • Must unlock in a finally block

Start with synchronized or an atomic class. Reach for ReentrantLock only when you need tryLock, fairness or multiple conditions.

The big ideas

What you need to know

synchronized

A synchronized method or block lets one thread at a time hold the object's lock. Others block until it is released.

Visibility too

Releasing a lock publishes your writes, and acquiring it sees them. Locks fix both atomicity and visibility.

ReentrantLock

From java.util.concurrent.locks. More flexible, but you must call unlock() yourself in finally.

Atomic classes

AtomicInteger.incrementAndGet() is a safe count++ without any lock. Great for simple counters.

See it in code

Walk through the code

java
1import java.util.concurrent.atomic.AtomicInteger;2import java.util.concurrent.locks.ReentrantLock;3 4class TicketCounter {5    private int sold = 0;6    private int refunded = 0;7    private final ReentrantLock refundLock = new ReentrantLock();8    private final AtomicInteger views = new AtomicInteger();9 10    public synchronized void sellOne() {11        sold++;12    }13 14    public void refund(int n) {15        refundLock.lock();16        try {17            refunded += n;18        } finally {19            refundLock.unlock();20        }21    }22 23    public void view() {24        views.incrementAndGet();25    }26}

1/3synchronized on the method locks this object. Only one thread can run sellOne at a time.

Three tools, three fields. Each field always uses one guard: sold uses the object lock, refunded uses refundLock, views is atomic.

Save yourself the pain

Common mistakes

Oops

Guarding one method with synchronized and another method on the same field with a ReentrantLock.

Do this instead

Every access to a shared field must use the same lock. Two different locks don't exclude each other. In the example, each field has exactly one guard.

Oops

Calling lock.unlock() at the end of the try block.

Do this instead

Put unlock() in finally. If the code throws, the lock would otherwise stay held forever.

Oops

Synchronizing everything just to be safe.

Do this instead

Hold locks for the shortest time and only around shared state. Too much locking makes threads wait and kills the speed you wanted.

Your mission

Fix the lost updates

~25 min

Quick check

Why should lock.unlock() go inside a finally block?

Go deeper

  1. 1Increment a shared counter from two threads and see the wrong result.
  2. 2Fix it with synchronized, then with AtomicInteger.
  3. 3Create a simple deadlock on purpose and understand why it happens.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge