Sleeping Barber Problem

Medium
ConcurrencySemaphoreProducer-ConsumerThread CoordinationMutex

Problem Statement

Simulate the classic Sleeping Barber problem. A barber shop has:

  • 1 barber: Sleeps when no customers are waiting; wakes up when a customer arrives.
  • N waiting chairs: Customers who find all chairs full leave (are turned away).
  • 1 barber chair: Where the current customer is served.

Customers arrive at random intervals. If the barber is busy and a waiting chair is available, the customer waits; otherwise the customer leaves.

class BarberShop {
    public BarberShop(int waitingChairs) {}
    // Called by barber thread
    public void barber() throws InterruptedException {}
    // Called by each customer thread (returns true if served, false if turned away)
    public boolean customer(int customerId) throws InterruptedException {}
    public int getCustomersServed() {}
    public int getCustomersTurnedAway() {}
}

Key Entities

  • Semaphore customers: Counts waiting customers (barber acquires this to start serving).
  • Semaphore barberReady: Customer waits on this until barber is ready to serve them.
  • Mutex waitingMutex: Protects waitingCount.
  • waitingCount: Number of customers currently in waiting chairs.

Requirements

  1. Barber sleeps when no customers are waiting and wakes on customer arrival.
  2. Customer leaves immediately if all N waiting chairs are occupied.
  3. No race conditions on waitingCount.
  4. System terminates cleanly when told to close (no more customers arrive).

Asked at: Google, Amazon, Microsoft, Oracle, Uber

!Constraints

- 1 ≤ waitingChairs ≤ 20 - Customers arrive concurrently from multiple threads. - Barber runs in a dedicated loop thread. - Haircut duration is simulated by a configurable sleep time.
Output

Run or submit your code to see output here.