Skip to lesson

synchronized blocks and which object is the lock

A synchronized block locks one chosen object for just a few lines of code. The code inside is protected only against threads that lock the same object, so picking the lock object is the real decision.

synchronized (this) versus a private final lock object

A lock, or monitor, is held by one thread at a time; every Java object has one, and synchronized code must get it before running.

A synchronized block is written synchronized (lockObject) { ... }. The thread takes the lock of lockObject before the braces and releases it after them.

Many teams prefer a private final lock object: private final Object lock = new Object();. The code below uses one.

Example 1 · A counter guarded by a private lock

PrivateLockCounterDemo.javaJava
class Counter {    private final Object lock = new Object();   // only this class can use it    private int count = 0;
    void increment() {        synchronized (lock) {            count++;        }    }
    int get() {        synchronized (lock) {            return count;        }    }}
public class PrivateLockCounterDemo {    public static void main(String[] args) throws InterruptedException {        Counter counter = new Counter();        Runnable task = () -> {            for (int i = 0; i < 1_000_000; i++) {                counter.increment();            }        };        Thread a = new Thread(task, "adder-1");        Thread b = new Thread(task, "adder-2");        a.start();        b.start();        a.join();        b.join();        System.out.println("Count: " + counter.get());    }}
Output
Count: 2000000

What this code does

  • Both methods lock the same lock object, so count++ and the read never overlap with another thread's update. The result is right on every run.
  • This behaves like synchronized methods, but the lock is hidden inside the class. Code outside cannot take it, so it cannot accidentally slow down or block the counter.

Example 2 · Outside code holding the lock of this

OutsiderLockDemo.javaJava
class ThisLockedAccount {    private int balance;
    synchronized void deposit(int amount) {     // locks this        balance += amount;    }}
class PrivateLockAccount {    private final Object lock = new Object();    private int balance;
    void deposit(int amount) {        synchronized (lock) {                   // locks a private object            balance += amount;        }    }}
public class OutsiderLockDemo {    static long waitForDeposit(Object account, Runnable deposit) throws InterruptedException {        Thread outsider = new Thread(() -> {            synchronized (account) {                try {                    Thread.sleep(200);                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                }            }        }, "outsider");        outsider.start();        Thread.sleep(50);                       // the outsider now holds the account's lock        long start = System.nanoTime();        deposit.run();        long waitedMs = (System.nanoTime() - start) / 1_000_000;        outsider.join();        return waitedMs;    }
    public static void main(String[] args) throws InterruptedException {        ThisLockedAccount a = new ThisLockedAccount();        long w1 = waitForDeposit(a, () -> a.deposit(100));        System.out.println("Lock on this, deposit had to wait:    " + (w1 >= 100));
        PrivateLockAccount b = new PrivateLockAccount();        long w2 = waitForDeposit(b, () -> b.deposit(100));        System.out.println("Private lock, deposit had to wait:    " + (w2 >= 100));    }}
Sample output
Lock on this, deposit had to wait:    true
Private lock, deposit had to wait:    false

What this code does

  • The outsider thread locks the account object itself and sleeps. ThisLockedAccount.deposit needs that same lock, so it waits about 150 ms. PrivateLockAccount.deposit needs a different, hidden lock, so it runs at once.
  • The result depends on timing (the 50 ms pause in main), so it is a sample, but it comes out this way on almost every run. With a private lock, no outside code can hold up your class by accident.

It is private, so no code outside the class can take it and hold up your methods. It is final, so it can never be swapped for a different object halfway through the program.

Writing synchronized (this) { ... } uses the same lock as a synchronized method of that object. With this as the lock, any outside code that does synchronized (account) competes with the account's own methods. With a private lock, only the class itself decides who waits. A synchronized block releases its lock even if an exception leaves it.

Two threads locking different objects protect nothing

A lock protects shared data only when every thread uses the same lock object for that data.

This bug hides well, because the code looks locked.

Example 3 · Mistake: each worker brings its own lock

WrongLockDemo.javaJava
class Scoreboard {    int runs = 0;}
class Batter implements Runnable {    private final Object lock = new Object();   // a different lock for every Batter    private final Scoreboard board;
    Batter(Scoreboard board) {        this.board = board;    }
    @Override    public void run() {        for (int i = 0; i < 1_000_000; i++) {            synchronized (lock) {                board.runs++;            }        }    }}
public class WrongLockDemo {    public static void main(String[] args) throws InterruptedException {        Scoreboard board = new Scoreboard();        Thread rohit = new Thread(new Batter(board), "rohit");        Thread virat = new Thread(new Batter(board), "virat");        rohit.start();        virat.start();        rohit.join();        virat.join();        System.out.println("Runs: " + board.runs + " (should be 2000000)");    }}
Sample output
Runs: 1689243 (should be 2000000)

What this code does

  • Each Batter object has its own lock, so rohit and virat lock two different objects and never wait for each other. The shared board.runs still loses updates, and the number changes from run to run.
  • The code looks protected, which is why this bug survives code reviews. Ask one question: do all threads that touch this data lock the same object?

Example 4 · The fix: the lock lives with the data

RightLockDemo.javaJava
class Scoreboard {    private final Object lock = new Object();   // one lock, inside the shared object    private int runs = 0;
    void addRun() {        synchronized (lock) {            runs++;        }    }
    int runs() {        synchronized (lock) {            return runs;        }    }}
class Batter implements Runnable {    private final Scoreboard board;
    Batter(Scoreboard board) {        this.board = board;    }
    @Override    public void run() {        for (int i = 0; i < 1_000_000; i++) {            board.addRun();        }    }}
public class RightLockDemo {    public static void main(String[] args) throws InterruptedException {        Scoreboard board = new Scoreboard();        Thread rohit = new Thread(new Batter(board), "rohit");        Thread virat = new Thread(new Batter(board), "virat");        rohit.start();        virat.start();        rohit.join();        virat.join();        System.out.println("Runs: " + board.runs());    }}
Output
Runs: 2000000

What this code does

  • There is one Scoreboard and therefore one lock. Both batters go through addRun(), so both use the same lock and the total is right on every run.
  • runs is now private, so a Batter cannot change it without the lock even by mistake. Keeping the lock inside the class that owns the data is the habit that prevents this whole family of bugs.

Common causes are a lock field inside each worker object instead of inside the shared data, and synchronized (new Object()), which makes a fresh lock on every call. If thread A locks object X and thread B locks object Y, they never wait for each other, and the data is as unsafe as with no lock at all.

The safest habit is to keep the lock next to the data it protects, inside the same class. Then every caller goes through that class's methods and automatically uses the right lock.

Never lock on String literals or boxed Integers

String literals are shared across the whole JVM: every "lock" written anywhere in any class is the very same object. If two unrelated classes both lock on "lock", they block each other for no reason, and can even get stuck waiting for each other.

SameStringDemo.javaJava
class Hostel {    static final String LOCK = "lock";}
class Library {    static final String LOCK = "lock";}
public class SameStringDemo {    public static void main(String[] args) {        System.out.println(Hostel.LOCK == Library.LOCK);    }}
Output
true

Boxed values such as Integer are a different trap. seats-- on an Integer makes a new Integer object, so the lock object changes after every update and threads end up holding different locks. Small values from -128 to 127 are also cached and shared JVM-wide. Since Java 16, javac warns: "attempt to synchronize on an instance of a value-based class".

Example 5 · Mistake: locking on a boxed Integer

IntegerLockDemo.javaJava
public class IntegerLockDemo {    static Integer seatsLeft = 1_000_000;
    public static void main(String[] args) throws InterruptedException {        Runnable booker = () -> {            for (int i = 0; i < 500_000; i++) {                synchronized (seatsLeft) {      // the lock object changes below                    seatsLeft--;                // makes a NEW Integer object                }            }        };        Thread a = new Thread(booker, "booker-1");        Thread b = new Thread(booker, "booker-2");        a.start();        b.start();        a.join();        b.join();        System.out.println("Seats left: " + seatsLeft + " (should be 0)");    }}
Sample output
Seats left: 148120 (should be 0)

What this code does

  • seatsLeft-- unboxes the value, subtracts and boxes the result into a new Integer. The next thread then locks that new object while another thread may still hold the old one, so the threads often use different locks and updates are lost.
  • javac warns about this line: attempt to synchronize on an instance of a value-based class. The fix is a separate private static final Object lock = new Object(); and an int field.

Lock on an object you created yourself for that purpose, such as a private final Object lock.

Reentrancy: a thread can take a lock it already holds

Java's built-in locks are reentrant: a thread that already holds a lock can take it again without waiting for itself. The JVM keeps a count, and the lock is truly released only when the thread leaves the last block or method that took it.

Example 6 · Reentrancy: a synchronized method calls another

ReentrancyDemo.javaJava
class TicketDesk {    private int sold = 0;    private int fees = 0;
    synchronized void sell(int fee) {        sold++;        addFee(fee);                       // needs the same lock, already held        System.out.println("sell:   holds lock? " + Thread.holdsLock(this));    }
    synchronized void addFee(int fee) {        fees += fee;        System.out.println("addFee: holds lock? " + Thread.holdsLock(this));    }
    synchronized String report() {        return "Sold: " + sold + ", fees: Rs " + fees;    }}
public class ReentrancyDemo {    public static void main(String[] args) throws InterruptedException {        TicketDesk desk = new TicketDesk();        Thread clerk = new Thread(() -> desk.sell(30), "clerk");        clerk.start();        clerk.join();        System.out.println(desk.report());        System.out.println("main holds lock? " + Thread.holdsLock(desk));    }}
Output
addFee: holds lock? true
sell:   holds lock? true
Sold: 1, fees: Rs 30
main holds lock? false

What this code does

  • The clerk thread enters sell and takes the lock of desk. Inside, addFee needs the same lock; because the lock is reentrant, the thread simply enters again instead of waiting for itself.
  • The JVM counts the two entries. After addFee returns the thread still holds the lock (the second line), and only when sell returns is it released, so main can then call report().

This is what lets one synchronized method call another synchronized method on the same object, or a subclass's synchronized method call super's. Without reentrancy the thread would wait forever for a lock it holds itself. Reentrancy applies only to the same thread. A different thread still waits until the count drops to zero.

Next step

Check your understanding

12 quick questions