Unisex Bathroom Problem
A synchronization practice problem requiring us to synchronize the usage of a single bathroom by both the genders.
We'll cover the following...
Problem Statement
A bathroom is being designed for the use of both males and females in an office but requires the following constraints to be maintained:
- There cannot be men and women in the bathroom at the same time.
- There should never be more than three employees in the bathroom simultaneously.
The solution should avoid deadlocks. For now, though, don’t worry about starvation.
Solution
First let us come up with the skeleton of our Unisex Bathroom class. We want to model the problem programmatically first. We’ll need two APIs, one that is called by a male to use the bathroom and another one that is called by the woman to use the bathroom. Initially our class looks like the following
public class UnisexBathroom {
void maleUseBathroom(String name) throws InterruptedException {
}
void femaleUseBathroom(String name) throws InterruptedException {
}
}
Let us try to address the first problem of allowing either men or women to use the bathroom. We’ll worry about the max employees later. We need to maintain state in a variable which would tell us which gender is currently using the bathroom. Let’s call this variable inUseBy
. To make the code more readable we’ll make the type of the variable inUseBy
a string which can take on the values men, women or none.
We’ll also have a method useBathroom()
that’ll mock a person ...