-
Notifications
You must be signed in to change notification settings - Fork 0
/
Receptionist.java
45 lines (45 loc) · 1.33 KB
/
Receptionist.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.concurrent.Semaphore;
public class Receptionist {
private static Semaphore sem = new Semaphore(1, true); // declares a
// semaphore with
// 1 permit, as there is
// only 1 receptionist
private static Receptionist receptionistInstance = new Receptionist(); // One
// Receptionist
// Object
// only
private Receptionist() {
// make it private as we only have one receptionist
}
public static Receptionist getReceptionistInstance() {
return receptionistInstance;
}
// I have created two methods here because if there occurs some exception in
// the processing of doRegisterPatient method we are sure that we release
// the permit
public void registerPatient(Patient p) {
if(!p.isHasEntered() || p.isRegistered()) {
return;
}
try {
sem.acquire();
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
try {
doRegisterPatient(p);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
sem.release();
}
}
// Making this as private, as it is mend only for this class
private void doRegisterPatient(Patient p) throws InterruptedException {
System.out.println("Receptionist registers patient " + p.getId());
p.setRegistered(true);
System.out.println("Patient " + p.getId() + " leaves receptionist and sits in waiting room");
}
}