Lesson 27: Concurrency: synchronized & Race Conditions

28 Jul 2026 1 min Swarnil Singhai

Without synchronization, two threads updating shared state can interleave and corrupt it — synchronized makes an operation atomic.

Real-time example

A ticket-booking system without synchronization can sell the same last seat to two customers at once — a real bug that loses money.

class TicketPool {
    private int available = 1;
    synchronized boolean book() {
        if (available > 0) { available--; return true; }
        return false;
    }
}
// Two threads calling book() concurrently: only one gets true.

What's happening

synchronized ensures only one thread executes book() at a time on a given TicketPool instance — the race condition disappears.

Synchronize the smallest critical section possible — locking too much kills concurrency benefits entirely.

Advertisement