Skip to lesson

Synchronisation, critical sections and semaphores

"Two threads increment a counter. What can go wrong, and how do you fix it?" is a standard OS and Java question. The interviewer is checking that you can name the race, the critical section and the right tool.

Race condition example and the critical-section problem

Race condition is a bug where the result depends on the timing of two threads that use the same shared data, and at least one of them writes it.

The program below replays one bad timing by hand: two booking threads both read that one train seat is left, and both book it.

Example 1 · A lost update, step by step

LostUpdateDemo.javaJava
public class LostUpdateDemo {    static int seats = 1;   // one seat left on the train
    public static void main(String[] args) {        // Two booking threads, A and B, each run: read, check, write.        // We replay one bad interleaving by hand.        int aRead = seats;        int bRead = seats;        if (aRead > 0) seats = aRead - 1;        System.out.println("A booked, seats now " + seats);        if (bRead > 0) seats = bRead - 1;        System.out.println("B booked, seats now " + seats);        System.out.println("Tickets sold: 2 for 1 seat");    }}
Output
A booked, seats now 0
B booked, seats now 0
Tickets sold: 2 for 1 seat

What this code does

  • B read the value before A wrote it, so B's check used a stale value. Both bookings succeed and the seat is sold twice.
  • The fix is to make read-check-write one indivisible critical section, so B cannot read until A has finished.

count++ looks like one step but is three: load count, add 1, store it back. If two threads both load 5 before either stores, both store 6 and one increment is lost.

The critical section is the part of code that touches the shared data. The critical-section problem is designing an entry and exit protocol so threads take turns inside it. Race conditions are timing bugs: a program may pass a hundred runs and fail on the hundred-and-first. Revise: Why count++ is unsafe (opens in a new tab)

Order of execution

A lost update

Two threads run count++ with count = 5. Put the unlucky timing in order.

Mutual exclusion, progress and bounded waiting

Mutual exclusion means at most one process or thread is inside the critical section at any moment; it is the first of the three requirements.

Any correct solution to the critical-section problem must meet three requirements. Peterson's idea for two processes is shown below, followed by a program that gets mutual exclusion with synchronized and an atomic counter.

Text
// Peterson's solution for two processes i and j (classic textbook idea)flag[i] = true;          // I want to enterturn = j;                // but you may go firstwhile (flag[j] && turn == j) { }   // wait// critical sectionflag[i] = false;         // exit

Example 2 · Fixing a race with synchronized and AtomicInteger

CriticalSectionDemo.javaJava
import java.util.concurrent.atomic.AtomicInteger;
public class CriticalSectionDemo {    static int lockedCount = 0;    static final Object lock = new Object();    static AtomicInteger atomicCount = new AtomicInteger();
    public static void main(String[] args) throws InterruptedException {        Runnable work = () -> {            for (int i = 0; i < 100_000; i++) {                synchronized (lock) {          // entry section                    lockedCount++;             // critical section                }                              // exit section                atomicCount.incrementAndGet();            }        };        Thread t1 = new Thread(work);        Thread t2 = new Thread(work);        t1.start();        t2.start();        t1.join();        t2.join();        System.out.println("synchronized count: " + lockedCount);        System.out.println("atomic count:       " + atomicCount.get());    }}
Output
synchronized count: 200000
atomic count:       200000

What this code does

  • synchronized (lock) gives mutual exclusion: only one thread at a time runs lockedCount++, so no update is lost and the result is always 200000.
  • AtomicInteger uses a compare-and-swap instruction, so the whole increment happens as one step with no lock. Without either, the total would usually come out below 200000.

The three requirements interviewers ask for by name:

  • Mutual exclusion: at most one process is in the critical section at a time.
  • Progress: if no one is inside and some want to enter, one of them must be chosen soon; processes not trying to enter cannot block the choice.
  • Bounded waiting: after a process asks to enter, there is a limit on how many times others can enter before it.

Hardware helps with atomic instructions such as test-and-set and compare-and-swap; in Java that means synchronized, locks and atomic classes.

Fix the error

Fix the lock

Each snippet fails to compile. Pick the line that fixes it.

Round 1 of 2

A thread-safe counter that locks on a shared object.

static final Object LOCK = new Object();
static int count = 0;
static void add() {
synchronized (count) {
count++;
}
}

Error

error: unexpected type
  required: reference
  found:    int

Mutex vs binary vs counting semaphore

Semaphore is an integer changed only by two atomic operations, wait (P) and signal (V); a counting semaphore starts at N and lets up to N threads use a resource.

The program below lets eight students share three lab printers through a counting semaphore, and checks that never more than three print at once.

Example 3 · A counting semaphore for 3 lab printers

PrinterSemaphoreDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.concurrent.Semaphore;import java.util.concurrent.atomic.AtomicInteger;
public class PrinterSemaphoreDemo {    static final Semaphore printers = new Semaphore(3);   // 3 printers    static final AtomicInteger inUse = new AtomicInteger();    static final AtomicInteger maxSeen = new AtomicInteger();
    public static void main(String[] args) throws InterruptedException {        List<Thread> students = new ArrayList<>();        for (int i = 1; i <= 8; i++) {            Thread t = new Thread(() -> {                try {                    printers.acquire();                  // wait(P)                    int now = inUse.incrementAndGet();                    maxSeen.accumulateAndGet(now, Math::max);                    Thread.sleep(20);                    // printing                    inUse.decrementAndGet();                    printers.release();                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                }            });            students.add(t);            t.start();        }        for (Thread t : students) t.join();        System.out.println("8 students printed");        System.out.println("Never more than 3 at once: " + (maxSeen.get() <= 3));        System.out.println("Free printers at the end: " + printers.availablePermits());    }}
Output
8 students printed
Never more than 3 at once: true
Free printers at the end: 3

What this code does

  • acquire() is wait: it takes a permit or blocks when all 3 are taken. release() is signal: it returns a permit and wakes a waiting thread.
  • Eight students share three printers, and the check proves the semaphore never let a fourth one in. All 3 permits are back at the end.

wait (also called P or down) decrements the value and blocks if no permit is left; signal (V or up) increments it and wakes a waiting thread. A binary semaphore only takes the values 0 and 1.

A mutex also allows one user at a time, but it has ownership: only the thread that locked it should unlock it. A semaphore has no owner, so one thread can wait while another signals, which suits signalling between threads. Revise: Semaphore: limit access (opens in a new tab)

Predict the output

Permits left

Pick what the semaphore code prints.

Round 1 of 2

A semaphore with 2 permits gets one acquire and two releases.

Semaphore s = new Semaphore(2);
s.acquire();
s.release();
s.release();
System.out.println(s.availablePermits());
Java has java.util.concurrent.Semaphore (counting) and ReentrantLock or synchronized (mutex-style locks).

Producer-consumer and readers-writers at a high level

Producer-consumer is the bounded-buffer problem: producers add items to a buffer of size N and consumers remove them, so producers wait when it is full and consumers when it is empty.

Producers put items into a buffer of size N and consumers take them out. The classic solution uses three semaphores, shown below and in the program after it.

Text
Producer:                 Consumer:  wait(empty)               wait(full)  wait(mutex)               wait(mutex)  add item to buffer        remove item from buffer  signal(mutex)             signal(mutex)  signal(full)              signal(empty)

Example 4 · Producer-consumer with three semaphores

BoundedBufferDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;import java.util.concurrent.Semaphore;
public class BoundedBufferDemo {    static final int SIZE = 2;    static final Deque<Integer> buffer = new ArrayDeque<>();    static final Semaphore empty = new Semaphore(SIZE);  // free slots    static final Semaphore full = new Semaphore(0);      // filled slots    static final Semaphore mutex = new Semaphore(1);     // protects buffer
    public static void main(String[] args) throws InterruptedException {        Thread producer = new Thread(() -> {            try {                for (int order = 1; order <= 5; order++) {                    empty.acquire();                    mutex.acquire();                    buffer.addLast(order);                    mutex.release();                    full.release();                }            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        });        Thread consumer = new Thread(() -> {            try {                for (int k = 1; k <= 5; k++) {                    full.acquire();                    mutex.acquire();                    int order = buffer.removeFirst();                    mutex.release();                    empty.release();                    System.out.println("Warehouse packed order " + order);                }            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        });        producer.start();        consumer.start();        producer.join();        consumer.join();        System.out.println("Buffer empty at the end: " + buffer.isEmpty());    }}
Output
Warehouse packed order 1
Warehouse packed order 2
Warehouse packed order 3
Warehouse packed order 4
Warehouse packed order 5
Buffer empty at the end: true

What this code does

  • empty.acquire() blocks the producer (a web shop taking orders) when 2 orders are waiting; full.acquire() blocks the consumer (the warehouse) when there are none.
  • Orders come out in the same order they went in, because only the consumer prints and the buffer is FIFO. The order wait(empty) then wait(mutex) matters: reversed, the producer could hold the mutex while waiting for space, and the consumer could never get in.

empty starts at N and counts free slots, full starts at 0 and counts filled slots, and mutex starts at 1 and protects the buffer itself. The order wait(empty) then wait(mutex) matters: reversed, a producer could hold the mutex while waiting for space, and the consumer could never get in.

Readers-writers: many readers may read at the same time, but a writer needs the data alone. The first version favours readers, so writers can starve; Java's ReentrantReadWriteLock implements this idea. Dining philosophers is the third classic, used to show deadlock. Revise: Blocking queues compared (opens in a new tab) | ReadWriteLock for read-heavy data (opens in a new tab)

Order of execution

The producer for one item

Put the producer's steps for one item in the safe order.

Interview questions with model answers

Synchronisation questions test whether you can name the problem, the three requirements and the right tool. Expect follow-ups such as "Why can a binary semaphore not always replace a mutex?".

  • Must say: a race condition is a timing-dependent result on shared data.
  • Must say: the three requirements are mutual exclusion, progress and bounded waiting.
  • Must say: wait (P) decrements and may block; signal (V) increments and may wake.
  • Must say: a mutex has an owner; a semaphore has none.

Find the bug

Weak spoken answers

Each spoken answer has one wrong sentence. Click it.

Answer to "Mutex vs semaphore?"

Round 1 of 2

Next step

Check your understanding

12 quick questions