Synchronization

Race conditions and critical sections; mutexes, spinlocks, semaphores, condition variables, monitors, read-write locks and atomics — with correct code in Java, Python and TypeScript.

Advanced 3 min readLesson 7 of 16 Interview Q&A

When threads share data, the result can depend on the exact timing of their steps. That's a race condition, and it leads to the worst kind of bug: rare, timing-dependent and hard to reproduce. Synchronisation primitives let you control the interleaving.

A race in three instructions

count++ looks atomic but is really read → add → write:

Thread AThread Bread count (0)read count (0)add 1 → 1add 1 → 1write 1write 1
Two increments, final value 1: one update is lost.
Lost updates
class Counter {
    int count = 0;
    void inc() { count++; }        // NOT thread-safe
}
// Two threads × 1,000,000 increments → usually much less than 2,000,000

The critical-section problem

A critical section is code that accesses shared state. A correct solution must provide:

  1. Mutual exclusion — at most one thread inside at a time.
  2. Progress — if nobody is inside, someone who wants to enter eventually can.
  3. Bounded waiting — no thread waits forever (no starvation).

Mutex (lock)

class Counter {
    private int count = 0;
    private final ReentrantLock lock = new ReentrantLock();

    void inc() {
        lock.lock();
        try { count++; }
        finally { lock.unlock(); }     // always unlock, even on exceptions
    }

    // Or the built-in monitor:
    synchronized void inc2() { count++; }
}

How locks work underneath: an atomic hardware instruction (compare-and-swap or test-and-set) claims the lock. If it's taken, a spinlock loops, which is good for very short waits on multicore machines and in kernels, while a blocking mutex asks the OS to put the thread to sleep. Linux implements blocking locks with futexes: no syscall at all when there's no contention.

Semaphores

A semaphore is a counter with two atomic operations: wait/P (decrement; block if it would go below zero) and signal/V (increment; wake a waiter).

  • A binary semaphore (0/1) works like a lock.
  • A counting semaphore limits concurrency to N, e.g. at most 10 simultaneous database connections.
Semaphore permits = new Semaphore(10);
permits.acquire();
try { callDatabase(); } finally { permits.release(); }

Condition variables and monitors

A condition variable lets a thread wait (atomically releasing the lock) until some condition becomes true, and lets another thread wake it. Together with a lock this forms a monitor: Java's synchronized + wait/notifyAll is one.

A bounded blocking queue
class BoundedQueue<T> {
    private final Deque<T> q = new ArrayDeque<>();
    private final int cap;
    BoundedQueue(int cap) { this.cap = cap; }

    synchronized void put(T x) throws InterruptedException {
        while (q.size() == cap) wait();       // ALWAYS wait in a while loop
        q.addLast(x);
        notifyAll();
    }

    synchronized T take() throws InterruptedException {
        while (q.isEmpty()) wait();
        T x = q.removeFirst();
        notifyAll();
        return x;
    }
}
// In real code: java.util.concurrent.ArrayBlockingQueue

Read-write locks

Many readers may hold the lock at the same time; a writer needs exclusive access. Great for read-heavy data such as configuration or caches (ReentrantReadWriteLock, StampedLock in Java). Watch out for writer starvation.

Atomics and lock-free code

For simple shared counters and flags, hardware atomic operations avoid locks entirely:

AtomicInteger count = new AtomicInteger();
count.incrementAndGet();

// CAS loop: retry until no one else changed the value in between
int old, next;
do { old = count.get(); next = Math.max(old, candidate); }
while (!count.compareAndSet(old, next));

LongAdder hits = new LongAdder();     // better under heavy contention

Lock-free algorithms built on CAS (concurrent queues, ConcurrentHashMap) avoid blocking entirely but are hard to get right: beware the ABA problem and memory-ordering subtleties.

Choosing a primitive

NeedUse
Protect shared stateMutex / synchronized / with lock
Limit concurrency to NCounting semaphore
Wait until a condition holdsCondition variable (or a blocking queue)
Many readers, few writersRead-write lock
A single counter or flagAtomic variable
Hand work between threadsA concurrent queue — usually the best choice
Key takeaways
  • Race conditions come from unsynchronised read-modify-write on shared data.
  • Critical sections need mutual exclusion, progress and bounded waiting.
  • Mutexes for exclusion, semaphores for counting, condition variables for waiting on state.
  • Always wait in a while loop; always release locks in finally or a with block.
  • Atomics and CAS give lock-free counters; queues and immutability avoid sharing entirely.
Interview questions
QMutex vs semaphore?easy

A mutex provides mutual exclusion and has an owner: only the thread that locked it may unlock it. A semaphore is a counter that allows up to N concurrent holders and can be signalled by any thread, which makes it suitable for signalling and resource pools.

QIs i++ atomic in Java if i is volatile?medium

No. volatile guarantees visibility and ordering, but i++ is still a read, an add and a write. Use AtomicInteger or a lock.

QWhen is a spinlock better than a blocking mutex?hard

When critical sections are very short (shorter than the cost of sleeping and waking, a few microseconds), on multicore machines, and where sleeping isn't allowed (interrupt handlers in kernels). On a single core, or with long hold times, spinning wastes CPU.