Skip to lesson

Keep locked sections small

A lock should cover exactly the steps that must be atomic, and nothing more. Slow work inside a lock makes every other thread wait, but a lock that is too small lets another thread slip into the middle of an action.

Why slow work inside a lock makes everyone wait

Lock contention happens when several threads want the same lock at the same time. Only one can hold it; the rest sit in the BLOCKED state doing nothing.

Example 1 · Slow work inside versus outside the lock

LockSizeTimingDemo.javaJava
class Register {    private final Object lock = new Object();    private int entries = 0;
    void slowInside() {        synchronized (lock) {            entries++;            pause(50);                 // slow work while holding the lock        }    }
    void slowOutside() {        synchronized (lock) {            entries++;        }        pause(50);                     // slow work after releasing the lock    }
    int entries() {        synchronized (lock) {            return entries;        }    }
    static void pause(int ms) {        try {            Thread.sleep(ms);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
public class LockSizeTimingDemo {    static long timeFourThreads(Runnable job) throws InterruptedException {        Thread[] workers = new Thread[4];        for (int i = 0; i < workers.length; i++) {            workers[i] = new Thread(job, "worker-" + (i + 1));        }        long start = System.nanoTime();        for (Thread w : workers) {            w.start();        }        for (Thread w : workers) {            w.join();        }        return (System.nanoTime() - start) / 1_000_000;    }
    public static void main(String[] args) throws InterruptedException {        Register register = new Register();        long inside = timeFourThreads(register::slowInside);        long outside = timeFourThreads(register::slowOutside);        System.out.println("Slow work inside the lock:  " + inside + " ms");        System.out.println("Slow work outside the lock: " + outside + " ms");        System.out.println("Inside took about " + Math.round((double) inside / outside) + " times as long");        System.out.println("Entries: " + register.entries());    }}
Sample output
Slow work inside the lock:  226 ms
Slow work outside the lock: 61 ms
Inside took about 4 times as long
Entries: 8

What this code does

  • Inside the lock, the four 50 ms pauses happen one after another, so the run takes a little over 200 ms. Outside the lock they overlap and the run takes a little over 50 ms. Your exact times will differ, but inside stays about 4 times slower.
  • Both versions count correctly (8 entries for 8 calls), because entries++ is inside the lock either way. Only the slow part moved.

The longer a thread holds the lock, the longer everyone else waits. If each of four threads sleeps, prints, reads a file or calls a server for 50 ms while holding the lock, the four of them take about 200 ms, one after another. The same work done after releasing the lock runs in parallel and takes about 50 ms. So a lock turns the code inside it into a single queue. Keep that queue short.

Moving printing, files and network calls outside the lock

The critical section is the code that must run while holding the lock: the lines that read or change the shared data as one atomic action. Everything else belongs outside.

Example 2 · UPI payment: update under the lock, SMS outside

WalletSmsDemo.javaJava
class Wallet {    private final Object lock = new Object();    private int balance;
    Wallet(int balance) {        this.balance = balance;    }
    boolean pay(String shop, int amount) {        int left;        synchronized (lock) {                 // critical section: check and update            if (balance < amount) {                return false;            }            balance -= amount;            left = balance;                   // save what the SMS needs in a local        }        String sms = "Paid Rs " + amount + " to " + shop + ". Balance Rs " + left;        sendSms(sms);                         // slow, and touches no shared data        return true;    }
    int balance() {        synchronized (lock) {            return balance;        }    }
    private void sendSms(String text) {        try {            Thread.sleep(30);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
public class WalletSmsDemo {    public static void main(String[] args) throws InterruptedException {        Wallet wallet = new Wallet(1000);        boolean[] ok = new boolean[3];        Thread t1 = new Thread(() -> ok[0] = wallet.pay("Metro Mart", 200), "pay-1");        Thread t2 = new Thread(() -> ok[1] = wallet.pay("Bookshop", 300), "pay-2");        Thread t3 = new Thread(() -> ok[2] = wallet.pay("Book Store", 400), "pay-3");        t1.start();        t2.start();        t3.start();        t1.join();        t2.join();        t3.join();        int done = 0;        for (boolean b : ok) {            if (b) {                done++;            }        }        System.out.println("Payments done: " + done);        System.out.println("Final balance: Rs " + wallet.balance());    }}
Output
Payments done: 3
Final balance: Rs 100

What this code does

  • Only the check and the update of balance are inside the lock. The SMS text is built from the local left, and the slow sendSms (a 30 ms sleep that pretends to call the SMS gateway) runs after the lock is released, so the three payments do not wait for each other's SMS.
  • The check balance < amount and the subtraction stay together in one block. That keeps the balance correct: 200 + 300 + 400 = 900 is taken from 1000, leaving Rs 100 on every run.

Typical things to move out are System.out.println, building long strings, writing log files, sending an SMS or email and calling another server. They are slow and do not touch the shared fields. Save the values you need in local variables inside the lock, release it, then do the slow work with those locals. Calls to code you do not control, such as a listener or a callback, also belong outside the lock. You cannot know how long they take or which locks they take; the Classic Concurrency Bugs module shows how that can freeze a program.

Copy under the lock, use outside

A snapshot is a copy of shared data made while holding the lock. After the lock is released, the snapshot belongs to one thread only, so it can be sorted, printed or saved slowly without blocking anyone.

Example 3 · A quiz leaderboard: copy under the lock, sort outside

LeaderboardDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Score(String team, int points) {}
class Leaderboard {    private final Object lock = new Object();    private final List<Score> scores = new ArrayList<>();
    void add(String team, int points) {        synchronized (lock) {            scores.add(new Score(team, points));        }    }
    List<Score> snapshot() {        synchronized (lock) {            return new ArrayList<>(scores);       // a private copy for the caller        }    }}
public class LeaderboardDemo {    public static void main(String[] args) throws InterruptedException {        Leaderboard board = new Leaderboard();        Thread judge1 = new Thread(() -> {            board.add("Byte Busters", 42);            board.add("Null Pointers", 35);        }, "judge-1");        Thread judge2 = new Thread(() -> {            board.add("Code Storm", 48);            board.add("Stack Smashers", 39);        }, "judge-2");        judge1.start();        judge2.start();        judge1.join();        judge2.join();
        List<Score> copy = board.snapshot();     // lock held only while copying        copy.sort(Comparator.comparingInt(Score::points).reversed());        System.out.println("Top 3 at the college fest quiz:");        for (int i = 0; i < 3; i++) {            Score s = copy.get(i);            System.out.println((i + 1) + ". " + s.team() + " - " + s.points());        }    }}
Output
Top 3 at the college fest quiz:
1. Code Storm - 48
2. Byte Busters - 42
3. Stack Smashers - 39

What this code does

  • snapshot() holds the lock only while copying the list. The sorting and printing work on the private copy, so other judges could keep adding scores at the same time without waiting.
  • Sorting gives the same order on every run, even though the two judges add their scores in a different order each time.

The copy step must be inside the lock, so it never sees a half-done update. For a list, new ArrayList<>(shared) inside the block is enough. The snapshot can go out of date a moment later, which is fine for reports, screens and logs.

Too small: splitting one atomic action across two locks

A lock can also be too small. If the check is in one synchronized block and the act is in another, the lock is released in between, and another thread can run there. This is the check-then-act bug again, now with locks that look correct.

Example 4 · Mistake: the check and the act in two blocks

SplitLockDemo.javaJava
class Show {    private final Object lock = new Object();    private int seatsLeft = 1;
    boolean book() {        boolean free;        synchronized (lock) {           // block 1: check            free = seatsLeft > 0;        }        pause(50);                      // payment, with no lock held        if (free) {            synchronized (lock) {       // block 2: act                seatsLeft--;            }            return true;        }        return false;    }
    int seatsLeft() {        synchronized (lock) {            return seatsLeft;        }    }
    static void pause(int ms) {        try {            Thread.sleep(ms);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
public class SplitLockDemo {    public static void main(String[] args) throws InterruptedException {        Show show = new Show();        boolean[] booked = new boolean[2];        Thread asha = new Thread(() -> booked[0] = show.book(), "Asha");        Thread ravi = new Thread(() -> booked[1] = show.book(), "Ravi");        asha.start();        ravi.start();        asha.join();        ravi.join();        System.out.println("Asha booked: " + booked[0]);        System.out.println("Ravi booked: " + booked[1]);        System.out.println("Seats left: " + show.seatsLeft());    }}
Sample output
Asha booked: true
Ravi booked: true
Seats left: -1

What this code does

  • Every access to seatsLeft is locked, yet the last seat is sold twice. The lock is released between the check and the act, and during the payment both threads see a free seat.
  • This shows that "every line is synchronized" is not the goal. The goal is that each compound action runs under one lock from start to end. The result is timing-based, but the 50 ms payment makes it happen on almost every run.

Example 5 · The right size: reserve, pay outside, confirm or release

ReserveThenPayDemo.javaJava
class Show {    private final Object lock = new Object();    private int seatsLeft = 1;
    boolean book(boolean paymentWorks) {        synchronized (lock) {           // check and reserve: one atomic action            if (seatsLeft == 0) {                return false;            }            seatsLeft--;        }        pause(50);                      // slow payment, no lock held        if (!paymentWorks) {            synchronized (lock) {       // give the seat back                seatsLeft++;            }            return false;        }        return true;    }
    int seatsLeft() {        synchronized (lock) {            return seatsLeft;        }    }
    static void pause(int ms) {        try {            Thread.sleep(ms);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
public class ReserveThenPayDemo {    public static void main(String[] args) throws InterruptedException {        Show show = new Show();        boolean[] booked = new boolean[2];        Thread asha = new Thread(() -> booked[0] = show.book(true), "Asha");        Thread ravi = new Thread(() -> booked[1] = show.book(true), "Ravi");        asha.start();        ravi.start();        asha.join();        ravi.join();        int made = (booked[0] ? 1 : 0) + (booked[1] ? 1 : 0);        System.out.println("Bookings made: " + made);        System.out.println("Seats left: " + show.seatsLeft());    }}
Output
Bookings made: 1
Seats left: 0

What this code does

  • The check and the decrement now sit in one block, so only one thread can reserve the last seat. The slow payment still runs outside the lock, so other customers are never stuck behind it.
  • If a payment fails, the seat is released under the lock again. Which passenger wins changes from run to run, but exactly one booking is made every time.
  • Too big: safe, but threads queue up behind slow work.
  • Too small: fast, but other threads can break an action in the middle.
  • Right size: exactly the steps that must be atomic together.

The same mistake hides in calls like if (acc.getBalance() >= amt) acc.setBalance(acc.getBalance() - amt);. Each method is synchronized, but the pair is not atomic. The fix is one method, such as withdraw(amt), that does the whole action under one lock. The rule for lock size: the whole compound action goes inside one block, and slow work that does not touch shared data goes outside. When a slow step sits in the middle, such as a payment, reserve the seat under the lock, do the slow step outside, then confirm or release under the lock again.

Next step

Check your understanding

11 quick questions