Barber Shop

This lesson visits the synchronization issues when programmatically modeling a hypothetical barber shop and how they are solved using Java's concurrency primitives.

We'll cover the following...

Problem Statement

A similar problem appears in Silberschatz and Galvin’s OS book, and variations of this problem exist in the wild. A barbershop consists of a waiting room with n chairs, and a barber chair for giving haircuts. If there are no customers to be served, the barber goes to sleep. If a customer enters the barbershop and all chairs are occupied, then the customer leaves the shop. If the barber is busy, but chairs are available, then the customer sits in one of the free chairs. If the barber is asleep, the customer wakes up the barber. Write a program to coordinate the interaction between the barber and the customers.

Press + to interact
Barber Shop Problem
Barber Shop Problem

Solution

First of all, we need to understand the different state transitions for this problem before we devise a solution. Let’s look at them piecemeal:

  • A customer enters the shop and if all N chairs are occupied, he leaves. This hints at maintaining a count of the waiting customers.

  • If any of the N chairs is free, the customer takes up the chair to wait for his turn. Note this translates to using a semaphore on which threads that have found a free chair wait on before being called in by the barber for a haircut.

  • If a customer enters the shop and the barber is asleep it implies there are no customers in the shop. The just-entered customer thread wakes up the barber thread. This sounds like using a signaling ...