Skip to content
wannacode

Hotel reservations

Problem

One room, two confirmations

A small hotel has four rooms. Reservations come from everywhere: from the website, from the front desk, from travel agencies. One Friday evening, two agencies reserve the last double room in the same second. Both get a confirmation. On Saturday, two families arrive at the room.

We will build a system where the server keeps the rooms and the reservations, and clients send requests over the network. A client can:

  • see the free rooms;
  • check one room;
  • reserve a room in their own name;
  • cancel their own reservation.

And when two clients reserve the same room at the same time, only one of them succeeds. We will prove it with a program that gives the same output on every run.

We build from the bottom up: the model without a network, the rules and the errors, the protocol, the server and the client, the simultaneous requests, and finally everything in one program.

More precisely, if you are curious
The model is the same in Java and C#. In Java the clients send lines of text over a socket, and each client is in its own thread. In C# the server is a web service with ASP.NET Core, and the client calls it with HttpClient. In both languages the same key idea guards the rooms: synchronized.

The idea

The room

A room has a number, a type, a price per night and a state: free or taken.

class Room {
private final int number;
private final String type;
private final int price;
private boolean free = true;
public Room(int number, String type, int price) {
this.number = number;
this.type = type;
this.price = price;
}
public int getNumber() {
return number;
}
public String getType() {
return type;
}
public int getPrice() {
return price;
}
public boolean isFree() {
return free;
}
public void occupy() {
free = false;
}
public void release() {
free = true;
}
@Override
public String toString() {
return number + ", " + type + ", €" + price + " per night, " + (free ? "free" : "taken");
}
}
  • The number, the type and the price do not change. Only the state changes, and only through two methods with clear names: occupy and release.
  • The room does not know who is staying in it. The room goes out to every client who asks, and the guest's name should not leave the hotel.
More precisely, if you are curious
The state is boolean free. It could be text ("free", "taken", "under repair"), but then every comparison is with a string, and a typo is a bug. For more than two states you use an enumeration: enum RoomState { FREE, TAKEN, REPAIR }.

See it

The hotel and the reservation

The hotel keeps the rooms in a list and the guests in a dictionary "room number → name":
private final List<Room> rooms = new ArrayList<>();
private final Map<Integer, String> guests = new HashMap<>();
public void add(Room room) {
rooms.add(room);
}
public List<Room> freeRooms() {
return rooms.stream().filter(Room::isFree).toList();
}
public Room check(int number) {
return find(number);
}

find is private: it looks up the room by number or throws an exception. That way nobody from outside can grab a room and take it around the rules:

private Room find(int number) {
for (Room room : rooms) {
if (room.getNumber() == number) {
return room;
}
}
throw new RoomNotFoundException("There is no room " + number + ".");
}

The reservation checks the name, finds the room and checks whether it is free. Only then does it take it:

public void reserve(int number, String guest) {
if (guest.isBlank()) {
throw new HotelException("The guest's name is required.");
}
Room room = find(number);
if (!room.isFree()) {
throw new RoomTakenException("Room " + number + " is already taken.");
}
room.occupy();
guests.put(number, guest);
}
Hotel hotel = new Hotel();
hotel.add(new Room(101, "single", 60));
hotel.add(new Room(102, "double", 85));
hotel.add(new Room(201, "double", 95));
hotel.add(new Room(202, "suite", 140));
for (Room room : hotel.freeRooms()) {
System.out.println(room);
}
hotel.reserve(102, "Anna Petrova");
System.out.println("After the reservation: " + hotel.check(102));
System.out.println("Free rooms: " + hotel.freeRooms().size());
Output
101, single, €60 per night, free
102, double, €85 per night, free
201, double, €95 per night, free
202, suite, €140 per night, free
After the reservation: 102, double, €85 per night, taken
Free rooms: 3

The idea

Canceling and the rules

Not every request can be carried out: the room is taken, there is no room 305, a guest cancels someone else's reservation. These are refusals by the rules, so they are your own exceptions with a common parent:

class HotelException extends RuntimeException {
public HotelException(String message) {
super(message);
}
}
class RoomNotFoundException extends HotelException {
public RoomNotFoundException(String message) {
super(message);
}
}
class RoomTakenException extends HotelException {
public RoomTakenException(String message) {
super(message);
}
}

Canceling checks that the room is taken and that the same guest is canceling it:

public void cancel(int number, String guest) {
Room room = find(number);
if (room.isFree()) {
throw new HotelException("Room " + number + " is not reserved.");
}
if (!guests.get(number).equals(guest)) {
throw new HotelException("Room " + number + " is reserved by another guest.");
}
room.release();
guests.remove(number);
}

The project brief asks for the system to be checked in different scenarios: reserving, checking and canceling, both when they are valid and when they are not. Each scenario is a line in the output:

Hotel hotel = new Hotel();
hotel.add(new Room(101, "single", 60));
hotel.add(new Room(102, "double", 85));
hotel.add(new Room(201, "double", 95));
hotel.add(new Room(202, "suite", 140));
hotel.reserve(102, "Anna Petrova");
System.out.println("1. Free room: " + hotel.check(102));
try {
hotel.reserve(102, "Boris Iliev");
} catch (RoomTakenException e) {
System.out.println("2. Taken room: " + e.getMessage());
}
try {
hotel.cancel(102, "Boris Iliev");
} catch (HotelException e) {
System.out.println("3. Someone else's reservation: " + e.getMessage());
}
hotel.cancel(102, "Anna Petrova");
System.out.println("4. Cancellation: " + hotel.check(102));
try {
hotel.cancel(102, "Anna Petrova");
} catch (HotelException e) {
System.out.println("5. Second cancellation: " + e.getMessage());
}
try {
hotel.reserve(305, "Anna Petrova");
} catch (RoomNotFoundException e) {
System.out.println("6. No such room: " + e.getMessage());
}
try {
hotel.reserve(201, " ");
} catch (HotelException e) {
System.out.println("7. No name: " + e.getMessage());
}
Output
1. Free room: 102, double, €85 per night, taken
2. Taken room: Room 102 is already taken.
3. Someone else's reservation: Room 102 is reserved by another guest.
4. Cancellation: 102, double, €85 per night, free
5. Second cancellation: Room 102 is not reserved.
6. No such room: There is no room 305.
7. No name: The guest's name is required.

The specific exception says what the problem is. HotelException catches all refusals at once: the server will catch only that one and turn it into a reply for the client.

More precisely, if you are curious
  • The exceptions inherit from RuntimeException, so the methods do not write throws. A thread's run() and lambdas cannot throw checked exceptions.
  • Scenarios like these are natural tests. With JUnit each one becomes a method with @Test and assertThrows(RoomTakenException.class, () -> hotel.reserve(102, "Boris Iliev")).

Try it

Who is in 201

What will the program print?

Hotel hotel = new Hotel();
hotel.add(new Room(101, "single", 60));
hotel.add(new Room(102, "double", 85));
hotel.add(new Room(201, "double", 95));
hotel.add(new Room(202, "suite", 140));
hotel.reserve(101, "Anna Petrova");
hotel.reserve(201, "Boris Iliev");
hotel.cancel(101, "Anna Petrova");
try {
hotel.reserve(201, "Vera Koleva");
System.out.println("Vera is in 201");
} catch (RoomTakenException e) {
System.out.println("Vera is turned away");
}
System.out.println(hotel.freeRooms().size());
Answer

The idea

The protocol: a "COMMAND:text" line

Every message is one line COMMAND:text, and the server answers with one line:

The client sends The server answers
FREE OK: and the free rooms, separated by ;
CHECK:102 OK:102, double, €85 per night, taken
RESERVE:102;Anna Petrova OK:Room 102 is yours, Anna Petrova. or ERROR: and the reason
CANCEL:102;Anna Petrova OK:The reservation for room 102 is canceled. or ERROR: and the reason
EXIT BYE, and the server closes the connection

The words of the protocol are constants in one place:

class Protocol {
public static final String FREE = "FREE";
public static final String CHECK = "CHECK";
public static final String RESERVE = "RESERVE";
public static final String CANCEL = "CANCEL";
public static final String EXIT = "EXIT";
public static final String OK = "OK";
public static final String ERROR = "ERROR";
public static final String BYE = "BYE";
}

The reception translates a protocol line into a call to the hotel and back:

class Reception {
private final Hotel hotel;
public Reception(Hotel hotel) {
this.hotel = hotel;
}
...
}
public String handle(String line) {
int colon = line.indexOf(':');
String command = colon < 0 ? line : line.substring(0, colon);
String text = colon < 0 ? "" : line.substring(colon + 1);
try {
switch (command) {
case Protocol.FREE:
return Protocol.OK + ":" + join(hotel.freeRooms());
case Protocol.CHECK:
return Protocol.OK + ":" + hotel.check(number(text));
case Protocol.RESERVE:
return reserve(text);
case Protocol.CANCEL:
return cancel(text);
default:
throw new HotelException("Unknown command " + command + ".");
}
} catch (HotelException e) {
return Protocol.ERROR + ":" + e.getMessage();
}
}
private String reserve(String text) {
String[] parts = numberAndGuest(text);
int number = number(parts[0]);
hotel.reserve(number, parts[1]);
return Protocol.OK + ":Room " + number + " is yours, " + parts[1] + ".";
}
private String cancel(String text) {
String[] parts = numberAndGuest(text);
int number = number(parts[0]);
hotel.cancel(number, parts[1]);
return Protocol.OK + ":The reservation for room " + number + " is canceled.";
}
private static String[] numberAndGuest(String text) {
String[] parts = text.split(";", 2);
if (parts.length != 2) {
throw new HotelException("Write a number and a name, for example '102;Anna Petrova'.");
}
return parts;
}
private static int number(String text) {
try {
return Integer.parseInt(text.trim());
} catch (NumberFormatException e) {
throw new HotelException("The room number must be a whole number.");
}
}
private static String join(List<Room> rooms) {
if (rooms.isEmpty()) {
return "There are no free rooms.";
}
return String.join("; ", rooms.stream().map(Room::toString).toList());
}

The reception remembers nothing about the client: every line carries everything it needs, even the guest's name. That is why one reception is enough for all clients. You can check it without a network:

Hotel hotel = new Hotel();
hotel.add(new Room(101, "single", 60));
hotel.add(new Room(102, "double", 85));
hotel.add(new Room(201, "double", 95));
hotel.add(new Room(202, "suite", 140));
Reception reception = new Reception(hotel);
String[] lines = {
"RESERVE:102;Anna Petrova",
"CHECK:102",
"RESERVE:102;Boris Iliev",
"CANCEL:102",
"CHECK:one hundred two",
"SHOW"
};
for (String line : lines) {
System.out.println("> " + line);
System.out.println(reception.handle(line));
}
Output
> RESERVE:102;Anna Petrova
OK:Room 102 is yours, Anna Petrova.
> CHECK:102
OK:102, double, €85 per night, taken
> RESERVE:102;Boris Iliev
ERROR:Room 102 is already taken.
> CANCEL:102
ERROR:Write a number and a name, for example '102;Anna Petrova'.
> CHECK:one hundred two
ERROR:The room number must be a whole number.
> SHOW
ERROR:Unknown command SHOW.
More precisely, if you are curious
  • The commands could be an enumeration: enum Command { FREE, CHECK, RESERVE, CANCEL, EXIT }. Then they are a separate type with a closed list of values. In the course they are constants, because we have not covered enumerations.
  • The protocol is stateless: every line stands on its own. That makes it easy to check and easy to serve more clients. If the client first had to say "I am Anna", there would have to be one reception per client, like the session in the car dealership.

See it

The server

Each connected client gets its own ClientHandler, and the reception is shared:

class ClientHandler implements Runnable {
private final Socket socket;
private final Reception reception;
public ClientHandler(Socket socket, Reception reception) {
this.socket = socket;
this.reception = reception;
}
@Override
public void run() {
try (socket;
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
String line;
while ((line = in.readLine()) != null && !line.equals(Protocol.EXIT)) {
out.println(reception.handle(line));
}
out.println(Protocol.BYE);
} catch (IOException e) {
System.out.println("The connection to the client was lost: " + e.getMessage());
}
}
}

HotelServer accepts the clients in its own thread and hands each one to a pool of 10 threads:

class HotelServer {
private final ServerSocket serverSocket;
private final ExecutorService pool = Executors.newFixedThreadPool(10);
private final Reception reception;
public HotelServer(int port, Hotel hotel) throws IOException {
this.serverSocket = new ServerSocket(port);
this.reception = new Reception(hotel);
}
public void start() {
Thread acceptor = new Thread(() -> acceptAll());
acceptor.setDaemon(true);
acceptor.start();
}
private void acceptAll() {
while (true) {
try {
Socket client = serverSocket.accept();
pool.execute(new ClientHandler(client, reception));
} catch (IOException e) {
return;
}
}
}
public void stop() throws IOException {
serverSocket.close();
pool.shutdown();
}
}
  • Ten clients are served at once. The eleventh is accepted and waits in the pool's queue until someone leaves.
  • All ten threads call the same Hotel. So the hotel will have to guard its rooms. How, in a moment.

See it

The client

The client sends a line and reads the reply. close() says EXIT and closes the connection:
class HotelClient {
private final Socket socket;
private final BufferedReader in;
private final PrintWriter out;
public HotelClient(String host, int port) throws IOException {
socket = new Socket(host, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}
public String send(String command, String text) throws IOException {
out.println(command + ":" + text);
return in.readLine();
}
public String send(String command) throws IOException {
out.println(command);
return in.readLine();
}
public void close() throws IOException {
send(Protocol.EXIT);
socket.close();
}
}

The server and the client in one program:

Hotel hotel = new Hotel();
hotel.add(new Room(101, "single", 60));
hotel.add(new Room(102, "double", 85));
hotel.add(new Room(201, "double", 95));
hotel.add(new Room(202, "suite", 140));
HotelServer server = new HotelServer(5331, hotel);
server.start();
HotelClient client = new HotelClient("localhost", 5331);
System.out.println(client.send(Protocol.RESERVE, "102;Anna Petrova"));
System.out.println(client.send(Protocol.CHECK, "102"));
System.out.println(client.send(Protocol.FREE));
System.out.println(client.send(Protocol.CANCEL, "102;Anna Petrova"));
System.out.println(client.send(Protocol.CHECK, "305"));
client.close();
server.stop();
Output
OK:Room 102 is yours, Anna Petrova.
OK:102, double, €85 per night, taken
OK:101, single, €60 per night, free; 201, double, €95 per night, free; 202, suite, €140 per night, free
OK:The reservation for room 102 is canceled.
ERROR:There is no room 305.

The idea

Two for one room

A reservation is two steps: check that the room is free, then take it. If two requests run at the same time, this can happen:
Agency A Agency B
1 checks: 102 is free
2 checks: 102 is free
3 takes 102 for its guest
4 takes 102 for its guest and records that guest

Both get a confirmation. There is no mistake in any single line of code. The mistake is that the steps of the two requests interleave.

The fix: only one request at a time gets into the hotel. Then "check and take" is atomic: nobody can get in between the check and taking the room. In Java, synchronized on every public method of Hotel does this:
public synchronized void reserve(int number, String guest) {
if (guest.isBlank()) {
throw new HotelException("The guest's name is required.");
}
Room room = find(number);
if (!room.isFree()) {
throw new RoomTakenException("Room " + number + " is already taken.");
}
room.occupy();
guests.put(number, guest);
}

public synchronized void reserve(int number, String guest) {
if (guest.isBlank()) {
throw new HotelException("The guest's name is required.");
}
Room room = find(number);
if (!room.isFree()) {
throw new RoomTakenException("Room " + number + " is already taken.");
}
room.occupy();
guests.put(number, guest);
}
Step by step, in words
  1. Room 102 is free. Anna Petrova and Boris Iliev reserve it at the same moment.
  2. First without synchronized. This is one possible order: Anna's request checks and sees "free".
  3. Boris's request checks before Anna has taken the room: it sees "free" too.
  4. Anna takes the room and records her name.
  5. Boris takes the room too and records his name. Both have a confirmation for the same room.
  6. From the start, with synchronized: only one thread at a time gets into the hotel.
  7. Say Anna is first: she takes the lock. The check and the taking are one step, and nobody gets in between them.
  8. Boris reaches the hotel and waits until the lock is free.
  9. Boris has the lock. Now the check sees "taken".
  10. RoomTakenException. The reception sends it back as an error line, and Boris can ask for another room.
  11. The program from the lesson counts the ones that succeed: 1 for each room. Who was first is different on every run.

The proof: two clients reserve 102 at once, then twenty agencies reserve 201 at once. The replies are collected, and the program prints how many succeeded:

static String reserve(int port, int room, String guest) {
try {
HotelClient client = new HotelClient("localhost", port);
String reply = client.send(Protocol.RESERVE, room + ";" + guest);
client.close();
return reply;
} catch (IOException e) {
return Protocol.ERROR + ":" + e.getMessage();
}
}
static int race(int port, int room, String[] guests) throws InterruptedException {
String[] replies = new String[guests.length];
List<Thread> clients = new ArrayList<>();
for (int i = 0; i < guests.length; i++) {
int n = i;
Thread client = new Thread(() -> replies[n] = reserve(port, room, guests[n]));
clients.add(client);
client.start();
}
for (Thread client : clients) {
client.join();
}
int reserved = 0;
for (String reply : replies) {
if (reply.startsWith(Protocol.OK)) {
reserved++;
}
}
return reserved;
}
Hotel hotel = new Hotel();
hotel.add(new Room(101, "single", 60));
hotel.add(new Room(102, "double", 85));
hotel.add(new Room(201, "double", 95));
hotel.add(new Room(202, "suite", 140));
HotelServer server = new HotelServer(5332, hotel);
server.start();
String[] two = { "Anna Petrova", "Boris Iliev" };
System.out.println("Two for room 102, succeeded: " + race(5332, 102, two));
String[] agencies = new String[20];
for (int i = 0; i < agencies.length; i++) {
agencies[i] = "Agency " + (i + 1);
}
System.out.println("Twenty for room 201, succeeded: " + race(5332, 201, agencies));
HotelClient desk = new HotelClient("localhost", 5332);
System.out.println(desk.send(Protocol.FREE));
desk.close();
server.stop();
Output
Two for room 102, succeeded: 1
Twenty for room 201, succeeded: 1
OK:101, single, €60 per night, free; 202, suite, €140 per night, free
Each client is in its own thread and writes its reply to its own place in the array. main waits for all of them with join and counts the ones that succeeded.

Who won the room is different on every run, so the program does not print it. How many succeeded is always the same: one for each room.

More precisely, if you are curious
  • Without the locking the program would still almost always say 1: the window between the check and taking the room is small. But "almost always" means that once in thousands of reservations two guests arrive at the room. You do not catch a bug like that by running the program, but by thinking: which data is shared, and who changes it at the same time.
  • synchronized on a method locks the whole Hotel object. While one thread reserves 102, another waits even for 201. With four rooms that is fine. With thousands of rooms you lock per room, for example synchronized (room) { ... }.
  • In a real system the rooms are in a database, and the guarding happens there: a transaction or a condition in the query itself (UPDATE rooms SET free = false WHERE number = 102 AND free = true). Then it holds even with several servers, not only inside one program.

Try it

Locked, but not quite

A colleague split the reservation into two methods, both synchronized. The reception calls the check first, then the taking. With many requests at once, two people still sometimes get the same room. Which line is the bug on?

Pick the line with the bug.

See it

The whole hotel

The test scenarios from the brief, this time over the network, with two clients connected at once. At the end two people reserve 201 at the same moment:

static void say(String who, HotelClient client, String command, String text) throws IOException {
String reply = text.isEmpty() ? client.send(command) : client.send(command, text);
System.out.println(who + " > " + command + (text.isEmpty() ? "" : ":" + text));
System.out.println(who + " < " + reply);
}
Hotel hotel = new Hotel();
hotel.add(new Room(101, "single", 60));
hotel.add(new Room(102, "double", 85));
hotel.add(new Room(201, "double", 95));
hotel.add(new Room(202, "suite", 140));
HotelServer server = new HotelServer(5333, hotel);
server.start();
HotelClient anna = new HotelClient("localhost", 5333);
HotelClient boris = new HotelClient("localhost", 5333);
say("Anna", anna, Protocol.RESERVE, "102;Anna Petrova");
say("Boris", boris, Protocol.RESERVE, "102;Boris Iliev");
say("Boris", boris, Protocol.CHECK, "102");
say("Boris", boris, Protocol.CANCEL, "102;Boris Iliev");
say("Anna", anna, Protocol.CANCEL, "102;Anna Petrova");
say("Boris", boris, Protocol.RESERVE, "102;Boris Iliev");
say("Anna", anna, Protocol.CHECK, "305");
anna.close();
boris.close();
String[] two = { "Anna Petrova", "Vera Koleva" };
System.out.println("Two for room 201 at once, succeeded: " + race(5333, 201, two));
HotelClient desk = new HotelClient("localhost", 5333);
System.out.println(desk.send(Protocol.FREE));
desk.close();
server.stop();
Output
Anna > RESERVE:102;Anna Petrova
Anna < OK:Room 102 is yours, Anna Petrova.
Boris > RESERVE:102;Boris Iliev
Boris < ERROR:Room 102 is already taken.
Boris > CHECK:102
Boris < OK:102, double, €85 per night, taken
Boris > CANCEL:102;Boris Iliev
Boris < ERROR:Room 102 is reserved by another guest.
Anna > CANCEL:102;Anna Petrova
Anna < OK:The reservation for room 102 is canceled.
Boris > RESERVE:102;Boris Iliev
Boris < OK:Room 102 is yours, Boris Iliev.
Anna > CHECK:305
Anna < ERROR:There is no room 305.
Two for room 201 at once, succeeded: 1
OK:101, single, €60 per night, free; 202, suite, €140 per night, free
More precisely, if you are curious

The whole program, from start to finish:

Main.java
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
class Room {
private final int number;
private final String type;
private final int price;
private boolean free = true;
public Room(int number, String type, int price) {
this.number = number;
this.type = type;
this.price = price;
}
public int getNumber() {
return number;
}
public String getType() {
return type;
}
public int getPrice() {
return price;
}
public boolean isFree() {
return free;
}
public void occupy() {
free = false;
}
public void release() {
free = true;
}
@Override
public String toString() {
return number + ", " + type + ", €" + price + " per night, " + (free ? "free" : "taken");
}
}
class Hotel {
private final List<Room> rooms = new ArrayList<>();
private final Map<Integer, String> guests = new HashMap<>();
public synchronized void add(Room room) {
rooms.add(room);
}
public synchronized List<Room> freeRooms() {
return rooms.stream().filter(Room::isFree).toList();
}
public synchronized Room check(int number) {
return find(number);
}
public synchronized void reserve(int number, String guest) {
if (guest.isBlank()) {
throw new HotelException("The guest's name is required.");
}
Room room = find(number);
if (!room.isFree()) {
throw new RoomTakenException("Room " + number + " is already taken.");
}
room.occupy();
guests.put(number, guest);
}
public synchronized void cancel(int number, String guest) {
Room room = find(number);
if (room.isFree()) {
throw new HotelException("Room " + number + " is not reserved.");
}
if (!guests.get(number).equals(guest)) {
throw new HotelException("Room " + number + " is reserved by another guest.");
}
room.release();
guests.remove(number);
}
private Room find(int number) {
for (Room room : rooms) {
if (room.getNumber() == number) {
return room;
}
}
throw new RoomNotFoundException("There is no room " + number + ".");
}
}
class HotelException extends RuntimeException {
public HotelException(String message) {
super(message);
}
}
class RoomNotFoundException extends HotelException {
public RoomNotFoundException(String message) {
super(message);
}
}
class RoomTakenException extends HotelException {
public RoomTakenException(String message) {
super(message);
}
}
class Protocol {
public static final String FREE = "FREE";
public static final String CHECK = "CHECK";
public static final String RESERVE = "RESERVE";
public static final String CANCEL = "CANCEL";
public static final String EXIT = "EXIT";
public static final String OK = "OK";
public static final String ERROR = "ERROR";
public static final String BYE = "BYE";
}
class Reception {
private final Hotel hotel;
public Reception(Hotel hotel) {
this.hotel = hotel;
}
public String handle(String line) {
int colon = line.indexOf(':');
String command = colon < 0 ? line : line.substring(0, colon);
String text = colon < 0 ? "" : line.substring(colon + 1);
try {
switch (command) {
case Protocol.FREE:
return Protocol.OK + ":" + join(hotel.freeRooms());
case Protocol.CHECK:
return Protocol.OK + ":" + hotel.check(number(text));
case Protocol.RESERVE:
return reserve(text);
case Protocol.CANCEL:
return cancel(text);
default:
throw new HotelException("Unknown command " + command + ".");
}
} catch (HotelException e) {
return Protocol.ERROR + ":" + e.getMessage();
}
}
private String reserve(String text) {
String[] parts = numberAndGuest(text);
int number = number(parts[0]);
hotel.reserve(number, parts[1]);
return Protocol.OK + ":Room " + number + " is yours, " + parts[1] + ".";
}
private String cancel(String text) {
String[] parts = numberAndGuest(text);
int number = number(parts[0]);
hotel.cancel(number, parts[1]);
return Protocol.OK + ":The reservation for room " + number + " is canceled.";
}
private static String[] numberAndGuest(String text) {
String[] parts = text.split(";", 2);
if (parts.length != 2) {
throw new HotelException("Write a number and a name, for example '102;Anna Petrova'.");
}
return parts;
}
private static int number(String text) {
try {
return Integer.parseInt(text.trim());
} catch (NumberFormatException e) {
throw new HotelException("The room number must be a whole number.");
}
}
private static String join(List<Room> rooms) {
if (rooms.isEmpty()) {
return "There are no free rooms.";
}
return String.join("; ", rooms.stream().map(Room::toString).toList());
}
}
class ClientHandler implements Runnable {
private final Socket socket;
private final Reception reception;
public ClientHandler(Socket socket, Reception reception) {
this.socket = socket;
this.reception = reception;
}
@Override
public void run() {
try (socket;
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
String line;
while ((line = in.readLine()) != null && !line.equals(Protocol.EXIT)) {
out.println(reception.handle(line));
}
out.println(Protocol.BYE);
} catch (IOException e) {
System.out.println("The connection to the client was lost: " + e.getMessage());
}
}
}
class HotelServer {
private final ServerSocket serverSocket;
private final ExecutorService pool = Executors.newFixedThreadPool(10);
private final Reception reception;
public HotelServer(int port, Hotel hotel) throws IOException {
this.serverSocket = new ServerSocket(port);
this.reception = new Reception(hotel);
}
public void start() {
Thread acceptor = new Thread(() -> acceptAll());
acceptor.setDaemon(true);
acceptor.start();
}
private void acceptAll() {
while (true) {
try {
Socket client = serverSocket.accept();
pool.execute(new ClientHandler(client, reception));
} catch (IOException e) {
return;
}
}
}
public void stop() throws IOException {
serverSocket.close();
pool.shutdown();
}
}
class HotelClient {
private final Socket socket;
private final BufferedReader in;
private final PrintWriter out;
public HotelClient(String host, int port) throws IOException {
socket = new Socket(host, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}
public String send(String command, String text) throws IOException {
out.println(command + ":" + text);
return in.readLine();
}
public String send(String command) throws IOException {
out.println(command);
return in.readLine();
}
public void close() throws IOException {
send(Protocol.EXIT);
socket.close();
}
}
public class Main {
static void say(String who, HotelClient client, String command, String text) throws IOException {
String reply = text.isEmpty() ? client.send(command) : client.send(command, text);
System.out.println(who + " > " + command + (text.isEmpty() ? "" : ":" + text));
System.out.println(who + " < " + reply);
}
static String reserve(int port, int room, String guest) {
try {
HotelClient client = new HotelClient("localhost", port);
String reply = client.send(Protocol.RESERVE, room + ";" + guest);
client.close();
return reply;
} catch (IOException e) {
return Protocol.ERROR + ":" + e.getMessage();
}
}
static int race(int port, int room, String[] guests) throws InterruptedException {
String[] replies = new String[guests.length];
List<Thread> clients = new ArrayList<>();
for (int i = 0; i < guests.length; i++) {
int n = i;
Thread client = new Thread(() -> replies[n] = reserve(port, room, guests[n]));
clients.add(client);
client.start();
}
for (Thread client : clients) {
client.join();
}
int reserved = 0;
for (String reply : replies) {
if (reply.startsWith(Protocol.OK)) {
reserved++;
}
}
return reserved;
}
public static void main(String[] args) throws Exception {
Hotel hotel = new Hotel();
hotel.add(new Room(101, "single", 60));
hotel.add(new Room(102, "double", 85));
hotel.add(new Room(201, "double", 95));
hotel.add(new Room(202, "suite", 140));
HotelServer server = new HotelServer(5333, hotel);
server.start();
HotelClient anna = new HotelClient("localhost", 5333);
HotelClient boris = new HotelClient("localhost", 5333);
say("Anna", anna, Protocol.RESERVE, "102;Anna Petrova");
say("Boris", boris, Protocol.RESERVE, "102;Boris Iliev");
say("Boris", boris, Protocol.CHECK, "102");
say("Boris", boris, Protocol.CANCEL, "102;Boris Iliev");
say("Anna", anna, Protocol.CANCEL, "102;Anna Petrova");
say("Boris", boris, Protocol.RESERVE, "102;Boris Iliev");
say("Anna", anna, Protocol.CHECK, "305");
anna.close();
boris.close();
String[] two = { "Anna Petrova", "Vera Koleva" };
System.out.println("Two for room 201 at once, succeeded: " + race(5333, 201, two));
HotelClient desk = new HotelClient("localhost", 5333);
System.out.println(desk.send(Protocol.FREE));
desk.close();
server.stop();
}
}

Exercise

Keep going on your own

Work with the whole program from the previous card.

1. Changing rooms. The guest moves from one room to another with MOVE:102;202;Anna Petrova. The reply is OK:Anna Petrova is in room 202. If the new room is taken, the guest stays in the old one. The move is one method in Hotel, synchronized: nobody should take the new room between freeing the old one and taking the new one.

Output
OK:Room 102 is yours, Anna Petrova.
OK:Room 201 is yours, Boris Iliev.
ERROR:Room 201 is already taken.
OK:Anna Petrova is in room 202.
OK:101, single, €60 per night, free; 102, double, €85 per night, free

More ideas

  • Nights and total. A reservation is for a number of nights, and the confirmation says the total: "3 nights, €255".
  • Dates. A room is reserved for days, for example from December 14 to 16. Two reservations for the same room must not overlap. Whether the room is free depends on the dates.
  • My reservations. MINE:Anna Petrova says which rooms belong to this guest.
  • Waiting list. If the room is taken, the guest signs up to wait. When it is canceled, it goes to the first one on the list.
  • A client from the keyboard. A second program reads commands from the keyboard with Scanner and sends them to the server, which runs in another terminal.

Test

Check yourself

1. Two agencies reserve room 102 at the same moment, and the reservation is not synchronized. What can happen?
2. The "is it free" check and taking the room are in two separate synchronized methods. Is that enough?
3. Room 102 is taken. What does the client that sends RESERVE:102;Boris Iliev get?
4. Why does the program print how many reservations succeeded, and not who won the room?
5. Why are the guests' names in a dictionary in the hotel, and not in the room?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·