Bathroom Problem
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-03-05
Problem Statement
A single bathroom is shared by both Democrats (D) and Republicans (R) at a voting agency. The bathroom has the following constraints:
1.Capacity: Maximum of 3 people at a time.
•Mutual Exclusivity: At any moment, the bathroom may only be used by members of one political party. Mixed groups like (2D, 1R) or (1D, 1R) are not allowed.
•Allowed Combinations:
•Empty bathroom ()
•Only Democrats: (1D), (2D), (3D)
•Only Republicans: (1R), (2R), (3R)
•Usage Time: Each person takes f(N) seconds to use the bathroom, where f is a function based on the person’s name N and returns a variable time duration.
•Waiting Queue: People queue up while waiting to use the bathroom.
Requirements
•Implement this system using multithreading.
•Design a thread-safe queuing and scheduling mechanism that ensures:
•No mixed-party usage of the bathroom.
•Efficient utilization of the bathroom when space is available.
•The most eligible person(s) from the queue enter the bathroom as soon as conditions allow (based on fairness, arrival time, or other reasonable criteria).
Follow-Up: Starvation Prevention
Extend your solution to handle starvation prevention.
That is, modify your system so that one political party is not indefinitely blocked from accessing the bathroom if the other party keeps arriving continuously.
Solution
1import java.util.LinkedList;
2import java.util.Queue;
3import java.util.concurrent.locks.Condition;
4import java.util.concurrent.locks.ReentrantLock;
5
6interface IBathroomTaskWrapper {
7 void run() throws InterruptedException;
8
9 long getArrivalTime();
10
11 long getTaskTime();
12}
13
14class BathroomTask implements IBathroomTaskWrapper {
15 Runnable task;
16 long arrivalTime;
17 long taskTime;
18
19 BathroomTask(Runnable task, long arrivalTime, long taskTime) {
20 this.task = task;
21 this.arrivalTime = arrivalTime;
22 this.taskTime = taskTime;
23 }
24
25 public void run() throws InterruptedException {
26 this.task.run();
27 Thread.sleep(2000);
28 }
29
30 public long getArrivalTime() {
31 return this.arrivalTime;
32 }
33
34 public long getTaskTime() {
35 return this.taskTime;
36 }
37}
38
39
40class BathroomManager {
41 Queue<IBathroomTaskWrapper> democratQueue;
42 Queue<IBathroomTaskWrapper> republicanQueue;
43 ReentrantLock lock = new ReentrantLock();
44 Condition newDemocratAdded = lock.newCondition();
45 Condition newRepublicanAdded = lock.newCondition();
46 Condition userLeftBathroom = lock.newCondition();
47 int bathroomState = 0;
48 int peopleInBathroom = 0;
49
50 BathroomManager() {
51 democratQueue = new LinkedList<>();
52 republicanQueue = new LinkedList<>();
53
54 // start the processDemocrat thread
55 new Thread(() -> {
56 try {
57 this.processDemocrat();
58 } catch (InterruptedException e) {
59 throw new RuntimeException(e);
60 }
61 }).start();
62
63 // start the processRepublican thread
64 new Thread(() -> {
65 try {
66 this.processRepublican();
67 } catch (InterruptedException e) {
68 throw new RuntimeException(e);
69 }
70 }).start();
71 }
72
73 public void addDemocrat(Runnable task, long taskTime) {
74 lock.lock();
75 try {
76 BathroomTask democratTask = new BathroomTask(task, System.currentTimeMillis(), taskTime);
77 this.democratQueue.add(democratTask);
78 newDemocratAdded.signalAll();
79 } finally {
80 lock.unlock();
81 }
82 }
83
84 private void processDemocrat() throws InterruptedException {
85 while (true) {
86 this.lock.lock();
87 try {
88 while (this.democratQueue.isEmpty()) {
89 newDemocratAdded.await();
90 }
91
92 while (!canDemocratEnter()) {
93 userLeftBathroom.await();
94 }
95
96 IBathroomTaskWrapper nextDemocrat = this.democratQueue.remove();
97 bathroomState = 1;
98 peopleInBathroom++;
99 new Thread(() -> {
100 try {
101 scheduleUser(nextDemocrat);
102 } catch (InterruptedException e) {
103 throw new RuntimeException(e);
104 }
105 }).start();
106 } finally {
107 lock.unlock();
108 }
109 }
110 }
111
112 private boolean canDemocratEnter() {
113 if (bathroomState == 0) {
114 // Bathroom is free
115 return true;
116 }
117
118 if (bathroomState == 1 && peopleInBathroom < 3) {
119 // Democrats are already inside
120 return true;
121 }
122
123 // bathroomState == 2 and it's not empty — can't enter
124 return false;
125 }
126
127 private long getFirstDemocratArrivalTime() {
128 return this.democratQueue.isEmpty() ? Long.MAX_VALUE : this.democratQueue.peek().getArrivalTime();
129 }
130
131 private long getFirstRepublicanArrivalTime() {
132 return this.republicanQueue.isEmpty() ? Long.MAX_VALUE : this.republicanQueue.peek().getArrivalTime();
133 }
134
135 private void scheduleUser(IBathroomTaskWrapper bathroomTask) throws InterruptedException {
136 bathroomTask.run();
137
138 lock.lock();
139 try {
140 peopleInBathroom--;
141 if (peopleInBathroom == 0) {
142 bathroomState = 0;
143 }
144 userLeftBathroom.signalAll();
145 } finally {
146 lock.unlock();
147 }
148 }
149
150 public void addRepublican(Runnable task, long taskTime) {
151 lock.lock();
152 try {
153 BathroomTask republicanTask = new BathroomTask(task, System.currentTimeMillis(), taskTime);
154 this.republicanQueue.add(republicanTask);
155 newRepublicanAdded.signalAll();
156 } finally {
157 lock.unlock();
158 }
159 }
160
161 private void processRepublican() throws InterruptedException {
162 while (true) {
163 this.lock.lock();
164 try {
165 while (this.republicanQueue.isEmpty()) {
166 newRepublicanAdded.await();
167 }
168
169 while (!canRepublicanEnter()) {
170 userLeftBathroom.await();
171 }
172 bathroomState = 2;
173 peopleInBathroom++;
174
175 IBathroomTaskWrapper nextRepublican = (BathroomConcurrency.IBathroomTaskWrapper) this.republicanQueue.remove();
176 new Thread(() -> {
177 try {
178 scheduleUser(nextRepublican);
179 } catch (InterruptedException e) {
180 throw new RuntimeException(e);
181 }
182 }).start();
183 } finally {
184 lock.unlock();
185 }
186 }
187 }
188
189 private boolean canRepublicanEnter() {
190 if (bathroomState == 0) {
191 // Bathroom is free
192 return true;
193 }
194
195 if (bathroomState == 2 && peopleInBathroom < 3) {
196 // Republicans are already inside
197 return true;
198 }
199
200 // bathroomState == 1 and it's not empty — can't enter
201 return false;
202 }
203}
204
205public class Bathroom3 {
206 public static void main(String[] args) {
207 try {
208 BathroomManager bm = new BathroomManager();
209 bm.addDemocrat(() -> System.out.println("dem1 using bathroom"), 1000);
210 Thread.sleep(1000);
211 bm.addRepublican(() -> System.out.println("rep1 using bathroom"), 2000);
212 bm.addDemocrat(() -> System.out.println("dem2 using bathroom"), 1000);
213 Thread.sleep(1000);
214 bm.addDemocrat(() -> System.out.println("dem3 using bathroom"), 3000);
215 bm.addDemocrat(() -> System.out.println("dem4 using bathroom"), 1000);
216 bm.addDemocrat(() -> System.out.println("dem5 using bathroom"), 2000);
217 Thread.sleep(1000);
218 bm.addRepublican(() -> System.out.println("rep2 using bathroom"), 3000);
219 System.out.println("hlo");
220 } catch (Exception ex) {
221
222 }
223 }
224}For follow up:
We can use a rate limiter. The implementation is left for excercise.