Reservas de hotel
En resumen: Un proyecto de reservas de hotel: un servidor y muchos clientes reservan, consultan y anulan habitaciones a la vez, y cuando dos personas quieren la misma habitación en el mismo instante, solo una lo consigue.
Problema
Una habitación, dos confirmaciones
Un hotel pequeño tiene cuatro habitaciones. Las reservas llegan de todas partes: del sitio web, de la recepción, de las agencias de viajes. Un viernes por la tarde, dos agencias reservan la última habitación doble en el mismo segundo. Las dos reciben una confirmación. El sábado llegan dos familias a la habitación.
Vamos a construir un sistema en el que el servidor guarda las habitaciones y las reservas, y los clientes envían solicitudes por la red. Un cliente puede:
- ver las habitaciones libres;
- consultar una habitación;
- reservar una habitación a su nombre;
- anular su propia reserva.
Y cuando dos clientes reservan la misma habitación a la vez, solo uno de ellos lo consigue. Lo demostraremos con un programa que da la misma salida en cada ejecución.
Construimos de abajo arriba: el modelo sin red, las reglas y los errores, el protocolo, el servidor y el cliente, las solicitudes simultáneas y, al final, todo en un solo programa.
Más precisamente, para curiosos
HttpClient. En los dos lenguajes la misma idea clave protege las habitaciones: synchronized.La idea
La habitación
Una habitación tiene un número, un tipo, un precio por noche y un estado: libre u ocupada.
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 + " € por noche, " + (free ? "libre" : "ocupada"); }}public class Room{ public int Number { get; } public string Type { get; } public int Price { get; } public bool IsFree { get; set; } = true;
public Room(int number, string type, int price) { Number = number; Type = type; Price = price; }
public void Occupy() { IsFree = false; }
public void Release() { IsFree = true; }
public override string ToString() { return Number + ", " + Type + ", " + Price + " € por noche, " + (IsFree ? "libre" : "ocupada"); }}class Room: def __init__(self, number, kind, price): self._number = number self._kind = kind self._price = price self._free = True
@property def number(self): return self._number
@property def kind(self): return self._kind
@property def price(self): return self._price
@property def is_free(self): return self._free
def occupy(self): self._free = False
def release(self): self._free = True
def __str__(self): state = "libre" if self._free else "ocupada" return f"{self._number}, {self._kind}, {self._price} € por noche, {state}"class Room { #number; #type; #price; #free = true;
constructor(number, type, price) { this.#number = number; this.#type = type; this.#price = price; }
get number() { return this.#number; }
get type() { return this.#type; }
get price() { return this.#price; }
get isFree() { return this.#free; }
occupy() { this.#free = false; }
release() { this.#free = true; }
toString() { const state = this.#free ? "libre" : "ocupada"; return `${this.#number}, ${this.#type}, ${this.#price} € por noche, ${state}`; }}- El número, el tipo y el precio no cambian. Solo cambia el estado, y solo a través de dos métodos con nombres claros:
occupyyrelease. - La habitación no sabe quién se aloja en ella. La habitación sale hacia cualquier cliente que pregunte, y el nombre del huésped no debe salir del hotel.
Más precisamente, para curiosos
boolean free. Podría ser texto («libre», «ocupada», «en reparación»), pero entonces cada comparación es con una cadena, y una errata es un error. Para más de dos estados se usa una enumeración: enum RoomState { FREE, TAKEN, REPAIR }.Míralo
El hotel y la reserva
private final List<Room> rooms = new ArrayList<>();private final Map<Integer, String> guests = new HashMap<>();private readonly List<Room> rooms = new List<Room>();private readonly Dictionary<int, string> guests = new Dictionary<int, string>();def __init__(self): self._rooms = [] self._guests = {}#rooms = [];#guests = new Map();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);}public void Add(Room room){ rooms.Add(room);}
public List<Room> FreeRooms(){ return rooms.Where(room => room.IsFree).ToList();}
public Room Check(int number){ return Find(number);}def add(self, room): self._rooms.append(room)
def free_rooms(self): return [room for room in self._rooms if room.is_free]
def check(self, number): return self._find(number)add(room) { this.#rooms.push(room);}
freeRooms() { return this.#rooms.filter((room) => room.isFree);}
check(number) { return this.#find(number);}find es privado: busca la habitación por número o lanza una excepción. Así nadie de fuera puede agarrar una habitación y ocuparla saltándose las reglas:
private Room find(int number) { for (Room room : rooms) { if (room.getNumber() == number) { return room; } } throw new RoomNotFoundException("No existe la habitación " + number + ".");}private Room Find(int number){ Room room = rooms.FirstOrDefault(r => r.Number == number); if (room == null) { throw new RoomNotFoundException("No existe la habitación " + number + "."); } return room;}def _find(self, number): for room in self._rooms: if room.number == number: return room raise RoomNotFoundError(f"No existe la habitación {number}.")#find(number) { const room = this.#rooms.find((r) => r.number === number); if (room === undefined) { throw new RoomNotFoundError(`No existe la habitación ${number}.`); } return room;}La reserva comprueba el nombre, busca la habitación y comprueba si está libre. Solo entonces la ocupa:
public void reserve(int number, String guest) { if (guest.isBlank()) { throw new HotelException("El nombre del huésped es obligatorio."); } Room room = find(number); if (!room.isFree()) { throw new RoomTakenException("La habitación " + number + " ya está ocupada."); } room.occupy(); guests.put(number, guest);}public void Reserve(int number, string guest){ if (string.IsNullOrWhiteSpace(guest)) { throw new HotelException("El nombre del huésped es obligatorio."); } Room room = Find(number); if (!room.IsFree) { throw new RoomTakenException("La habitación " + number + " ya está ocupada."); } room.Occupy(); guests[number] = guest;}def reserve(self, number, guest): if not guest.strip(): raise HotelError("El nombre del huésped es obligatorio.") room = self._find(number) if not room.is_free: raise RoomTakenError(f"La habitación {number} ya está ocupada.") room.occupy() self._guests[number] = guestreserve(number, guest) { if (guest.trim() === "") { throw new HotelError("El nombre del huésped es obligatorio."); } const room = this.#find(number); if (!room.isFree) { throw new RoomTakenError(`La habitación ${number} ya está ocupada.`); } room.occupy(); this.#guests.set(number, guest);}Hotel hotel = new Hotel();hotel.add(new Room(101, "individual", 60));hotel.add(new Room(102, "doble", 85));hotel.add(new Room(201, "doble", 95));hotel.add(new Room(202, "suite", 140));
for (Room room : hotel.freeRooms()) { System.out.println(room);}hotel.reserve(102, "Ana Torres");System.out.println("Después de la reserva: " + hotel.check(102));System.out.println("Habitaciones libres: " + hotel.freeRooms().size());101, individual, 60 € por noche, libre102, doble, 85 € por noche, libre201, doble, 95 € por noche, libre202, suite, 140 € por noche, libreDespués de la reserva: 102, doble, 85 € por noche, ocupadaHabitaciones libres: 3Hotel hotel = new Hotel();hotel.Add(new Room(101, "individual", 60));hotel.Add(new Room(102, "doble", 85));hotel.Add(new Room(201, "doble", 95));hotel.Add(new Room(202, "suite", 140));
foreach (Room room in hotel.FreeRooms()){ Console.WriteLine(room);}hotel.Reserve(102, "Ana Torres");Console.WriteLine("Después de la reserva: " + hotel.Check(102));Console.WriteLine("Habitaciones libres: " + hotel.FreeRooms().Count);101, individual, 60 € por noche, libre102, doble, 85 € por noche, libre201, doble, 95 € por noche, libre202, suite, 140 € por noche, libreDespués de la reserva: 102, doble, 85 € por noche, ocupadaHabitaciones libres: 3hotel = Hotel()hotel.add(Room(101, "individual", 60))hotel.add(Room(102, "doble", 85))hotel.add(Room(201, "doble", 95))hotel.add(Room(202, "suite", 140))
for room in hotel.free_rooms(): print(room)hotel.reserve(102, "Ana Torres")print(f"Después de la reserva: {hotel.check(102)}")print(f"Habitaciones libres: {len(hotel.free_rooms())}")101, individual, 60 € por noche, libre102, doble, 85 € por noche, libre201, doble, 95 € por noche, libre202, suite, 140 € por noche, libreDespués de la reserva: 102, doble, 85 € por noche, ocupadaHabitaciones libres: 3const hotel = new Hotel();hotel.add(new Room(101, "individual", 60));hotel.add(new Room(102, "doble", 85));hotel.add(new Room(201, "doble", 95));hotel.add(new Room(202, "suite", 140));
for (const room of hotel.freeRooms()) { console.log(String(room));}hotel.reserve(102, "Ana Torres");console.log(`Después de la reserva: ${hotel.check(102)}`);console.log(`Habitaciones libres: ${hotel.freeRooms().length}`);101, individual, 60 € por noche, libre102, doble, 85 € por noche, libre201, doble, 95 € por noche, libre202, suite, 140 € por noche, libreDespués de la reserva: 102, doble, 85 € por noche, ocupadaHabitaciones libres: 3La idea
La anulación y las reglas
No toda solicitud se puede cumplir: la habitación está ocupada, no existe la habitación 305, un huésped anula la reserva de otro. Son rechazos según las reglas, así que son excepciones propias con un padre común:
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); }}public class HotelException : Exception{ public HotelException(string message) : base(message) { }}
public class RoomNotFoundException : HotelException{ public RoomNotFoundException(string message) : base(message) { }}
public class RoomTakenException : HotelException{ public RoomTakenException(string message) : base(message) { }}class HotelError(Exception): pass
class RoomNotFoundError(HotelError): pass
class RoomTakenError(HotelError): passclass HotelError extends Error { constructor(message) { super(message); this.name = "HotelError"; }}
class RoomNotFoundError extends HotelError { constructor(message) { super(message); this.name = "RoomNotFoundError"; }}
class RoomTakenError extends HotelError { constructor(message) { super(message); this.name = "RoomTakenError"; }}La anulación comprueba que la habitación esté ocupada y que la anule el mismo huésped:
public void cancel(int number, String guest) { Room room = find(number); if (room.isFree()) { throw new HotelException("La habitación " + number + " no está reservada."); } if (!guests.get(number).equals(guest)) { throw new HotelException("La habitación " + number + " está reservada por otro huésped."); } room.release(); guests.remove(number);}public void Cancel(int number, string guest){ Room room = Find(number); if (room.IsFree) { throw new HotelException("La habitación " + number + " no está reservada."); } if (guests[number] != guest) { throw new HotelException("La habitación " + number + " está reservada por otro huésped."); } room.Release(); guests.Remove(number);}def cancel(self, number, guest): room = self._find(number) if room.is_free: raise HotelError(f"La habitación {number} no está reservada.") if self._guests[number] != guest: raise HotelError(f"La habitación {number} está reservada por otro huésped.") room.release() del self._guests[number]cancel(number, guest) { const room = this.#find(number); if (room.isFree) { throw new HotelError(`La habitación ${number} no está reservada.`); } if (this.#guests.get(number) !== guest) { throw new HotelError(`La habitación ${number} está reservada por otro huésped.`); } room.release(); this.#guests.delete(number);}El enunciado del proyecto pide comprobar el sistema en distintos escenarios: reservar, consultar y anular, tanto cuando son válidos como cuando no lo son. Cada escenario es una línea de la salida:
Hotel hotel = new Hotel();hotel.add(new Room(101, "individual", 60));hotel.add(new Room(102, "doble", 85));hotel.add(new Room(201, "doble", 95));hotel.add(new Room(202, "suite", 140));
hotel.reserve(102, "Ana Torres");System.out.println("1. Habitación libre: " + hotel.check(102));try { hotel.reserve(102, "Bruno Silva");} catch (RoomTakenException e) { System.out.println("2. Habitación ocupada: " + e.getMessage());}try { hotel.cancel(102, "Bruno Silva");} catch (HotelException e) { System.out.println("3. Reserva ajena: " + e.getMessage());}hotel.cancel(102, "Ana Torres");System.out.println("4. Anulación: " + hotel.check(102));try { hotel.cancel(102, "Ana Torres");} catch (HotelException e) { System.out.println("5. Segunda anulación: " + e.getMessage());}try { hotel.reserve(305, "Ana Torres");} catch (RoomNotFoundException e) { System.out.println("6. No existe esa habitación: " + e.getMessage());}try { hotel.reserve(201, " ");} catch (HotelException e) { System.out.println("7. Sin nombre: " + e.getMessage());}1. Habitación libre: 102, doble, 85 € por noche, ocupada2. Habitación ocupada: La habitación 102 ya está ocupada.3. Reserva ajena: La habitación 102 está reservada por otro huésped.4. Anulación: 102, doble, 85 € por noche, libre5. Segunda anulación: La habitación 102 no está reservada.6. No existe esa habitación: No existe la habitación 305.7. Sin nombre: El nombre del huésped es obligatorio.Hotel hotel = new Hotel();hotel.Add(new Room(101, "individual", 60));hotel.Add(new Room(102, "doble", 85));hotel.Add(new Room(201, "doble", 95));hotel.Add(new Room(202, "suite", 140));
hotel.Reserve(102, "Ana Torres");Console.WriteLine("1. Habitación libre: " + hotel.Check(102));try{ hotel.Reserve(102, "Bruno Silva");}catch (RoomTakenException e){ Console.WriteLine("2. Habitación ocupada: " + e.Message);}try{ hotel.Cancel(102, "Bruno Silva");}catch (HotelException e){ Console.WriteLine("3. Reserva ajena: " + e.Message);}hotel.Cancel(102, "Ana Torres");Console.WriteLine("4. Anulación: " + hotel.Check(102));try{ hotel.Cancel(102, "Ana Torres");}catch (HotelException e){ Console.WriteLine("5. Segunda anulación: " + e.Message);}try{ hotel.Reserve(305, "Ana Torres");}catch (RoomNotFoundException e){ Console.WriteLine("6. No existe esa habitación: " + e.Message);}try{ hotel.Reserve(201, " ");}catch (HotelException e){ Console.WriteLine("7. Sin nombre: " + e.Message);}1. Habitación libre: 102, doble, 85 € por noche, ocupada2. Habitación ocupada: La habitación 102 ya está ocupada.3. Reserva ajena: La habitación 102 está reservada por otro huésped.4. Anulación: 102, doble, 85 € por noche, libre5. Segunda anulación: La habitación 102 no está reservada.6. No existe esa habitación: No existe la habitación 305.7. Sin nombre: El nombre del huésped es obligatorio.hotel = Hotel()hotel.add(Room(101, "individual", 60))hotel.add(Room(102, "doble", 85))hotel.add(Room(201, "doble", 95))hotel.add(Room(202, "suite", 140))
hotel.reserve(102, "Ana Torres")print(f"1. Habitación libre: {hotel.check(102)}")try: hotel.reserve(102, "Bruno Silva")except RoomTakenError as e: print(f"2. Habitación ocupada: {e}")try: hotel.cancel(102, "Bruno Silva")except HotelError as e: print(f"3. Reserva ajena: {e}")hotel.cancel(102, "Ana Torres")print(f"4. Anulación: {hotel.check(102)}")try: hotel.cancel(102, "Ana Torres")except HotelError as e: print(f"5. Segunda anulación: {e}")try: hotel.reserve(305, "Ana Torres")except RoomNotFoundError as e: print(f"6. No existe esa habitación: {e}")try: hotel.reserve(201, " ")except HotelError as e: print(f"7. Sin nombre: {e}")1. Habitación libre: 102, doble, 85 € por noche, ocupada2. Habitación ocupada: La habitación 102 ya está ocupada.3. Reserva ajena: La habitación 102 está reservada por otro huésped.4. Anulación: 102, doble, 85 € por noche, libre5. Segunda anulación: La habitación 102 no está reservada.6. No existe esa habitación: No existe la habitación 305.7. Sin nombre: El nombre del huésped es obligatorio.const hotel = new Hotel();hotel.add(new Room(101, "individual", 60));hotel.add(new Room(102, "doble", 85));hotel.add(new Room(201, "doble", 95));hotel.add(new Room(202, "suite", 140));
hotel.reserve(102, "Ana Torres");console.log(`1. Habitación libre: ${hotel.check(102)}`);try { hotel.reserve(102, "Bruno Silva");} catch (e) { if (!(e instanceof RoomTakenError)) throw e; console.log(`2. Habitación ocupada: ${e.message}`);}try { hotel.cancel(102, "Bruno Silva");} catch (e) { if (!(e instanceof HotelError)) throw e; console.log(`3. Reserva ajena: ${e.message}`);}hotel.cancel(102, "Ana Torres");console.log(`4. Anulación: ${hotel.check(102)}`);try { hotel.cancel(102, "Ana Torres");} catch (e) { if (!(e instanceof HotelError)) throw e; console.log(`5. Segunda anulación: ${e.message}`);}try { hotel.reserve(305, "Ana Torres");} catch (e) { if (!(e instanceof RoomNotFoundError)) throw e; console.log(`6. No existe esa habitación: ${e.message}`);}try { hotel.reserve(201, " ");} catch (e) { if (!(e instanceof HotelError)) throw e; console.log(`7. Sin nombre: ${e.message}`);}1. Habitación libre: 102, doble, 85 € por noche, ocupada2. Habitación ocupada: La habitación 102 ya está ocupada.3. Reserva ajena: La habitación 102 está reservada por otro huésped.4. Anulación: 102, doble, 85 € por noche, libre5. Segunda anulación: La habitación 102 no está reservada.6. No existe esa habitación: No existe la habitación 305.7. Sin nombre: El nombre del huésped es obligatorio.La excepción concreta dice cuál es el problema. HotelException atrapa todos los rechazos de una vez: el servidor atrapará solo esa y la convertirá en una respuesta para el cliente.
Más precisamente, para curiosos
-
Las excepciones heredan de
RuntimeException, así que los métodos no escribenthrows. Elrun()de un hilo y las lambdas no pueden lanzar excepciones comprobadas. - Escenarios como estos son tests naturales. Con JUnit cada uno se convierte en un método con
@TestyassertThrows(RoomTakenException.class, () -> hotel.reserve(102, "Bruno Silva")).
Pruébalo
¿Quién está en la 201?
¿Qué imprimirá el programa?
Hotel hotel = new Hotel();hotel.add(new Room(101, "individual", 60));hotel.add(new Room(102, "doble", 85));hotel.add(new Room(201, "doble", 95));hotel.add(new Room(202, "suite", 140));
hotel.reserve(101, "Ana Torres");hotel.reserve(201, "Bruno Silva");hotel.cancel(101, "Ana Torres");try { hotel.reserve(201, "Vera Gil"); System.out.println("Vera está en la 201");} catch (RoomTakenException e) { System.out.println("Rechazo para Vera");}System.out.println(hotel.freeRooms().size());Ana ocupa la 101 y después la libera. Bruno ocupa la 201, así que Vera recibe RoomTakenException, y la línea «Vera está en la 201» no se ejecuta. Solo la 201 está ocupada, así que hay tres habitaciones libres.
La idea
El protocolo: una línea «COMANDO:texto»
Cada mensaje es una línea COMANDO:texto, y el servidor responde con una línea:
| El cliente envía | El servidor responde |
|---|---|
LIBRES |
OK: y las habitaciones libres, separadas por ; |
CONSULTAR:102 |
OK:102, doble, 85 € por noche, ocupada |
RESERVAR:102;Ana Torres |
OK:La habitación 102 es tuya, Ana Torres. o ERROR: y el motivo |
ANULAR:102;Ana Torres |
OK:La reserva de la habitación 102 está anulada. o ERROR: y el motivo |
SALIR |
ADIÓS, y el servidor cierra la conexión |
Las palabras del protocolo son constantes en un solo lugar:
class Protocol { public static final String FREE = "LIBRES"; public static final String CHECK = "CONSULTAR"; public static final String RESERVE = "RESERVAR"; public static final String CANCEL = "ANULAR"; public static final String EXIT = "SALIR";
public static final String OK = "OK"; public static final String ERROR = "ERROR"; public static final String BYE = "ADIÓS";}La recepción traduce una línea del protocolo en una llamada al hotel y de vuelta:
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("Comando desconocido " + 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 + ":La habitación " + number + " es tuya, " + parts[1] + ".";}
private String cancel(String text) { String[] parts = numberAndGuest(text); int number = number(parts[0]); hotel.cancel(number, parts[1]); return Protocol.OK + ":La reserva de la habitación " + number + " está anulada.";}
private static String[] numberAndGuest(String text) { String[] parts = text.split(";", 2); if (parts.length != 2) { throw new HotelException("Escribe número y nombre, por ejemplo «102;Ana Torres»."); } return parts;}
private static int number(String text) { try { return Integer.parseInt(text.trim()); } catch (NumberFormatException e) { throw new HotelException("El número de la habitación es un número entero."); }}
private static String join(List<Room> rooms) { if (rooms.isEmpty()) { return "No hay habitaciones libres."; } return String.join("; ", rooms.stream().map(Room::toString).toList());}La recepción no recuerda nada del cliente: cada línea lleva todo lo que necesita, incluso el nombre del huésped. Por eso basta una recepción para todos los clientes. Puedes comprobarlo sin red:
Hotel hotel = new Hotel();hotel.add(new Room(101, "individual", 60));hotel.add(new Room(102, "doble", 85));hotel.add(new Room(201, "doble", 95));hotel.add(new Room(202, "suite", 140));
Reception reception = new Reception(hotel);String[] lines = { "RESERVAR:102;Ana Torres", "CONSULTAR:102", "RESERVAR:102;Bruno Silva", "ANULAR:102", "CONSULTAR:ciento dos", "MOSTRAR"};for (String line : lines) { System.out.println("> " + line); System.out.println(reception.handle(line));}> RESERVAR:102;Ana TorresOK:La habitación 102 es tuya, Ana Torres.> CONSULTAR:102OK:102, doble, 85 € por noche, ocupada> RESERVAR:102;Bruno SilvaERROR:La habitación 102 ya está ocupada.> ANULAR:102ERROR:Escribe número y nombre, por ejemplo «102;Ana Torres».> CONSULTAR:ciento dosERROR:El número de la habitación es un número entero.> MOSTRARERROR:Comando desconocido MOSTRAR.Más precisamente, para curiosos
-
Los comandos podrían ser una enumeración:
enum Command { FREE, CHECK, RESERVE, CANCEL, EXIT }. Entonces son un tipo aparte con una lista cerrada de valores. En el curso son constantes, porque no hemos visto las enumeraciones. - El protocolo no tiene estado: cada línea vale por sí misma. Eso lo hace fácil de comprobar y fácil para atender a más clientes. Si el cliente tuviera que decir primero «soy Ana», haría falta una recepción por cliente, como la sesión del concesionario de coches.
Míralo
El servidor
Cada cliente conectado recibe su propio ClientHandler, y la recepción es compartida:
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("Se cortó la conexión con el cliente: " + e.getMessage()); } }}HotelServer acepta a los clientes en su propio hilo y pasa cada uno a un grupo de 10 hilos:
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(); }}- Se atienden diez clientes a la vez. El undécimo es aceptado y espera en la cola del grupo hasta que alguien se vaya.
- Los diez hilos llaman al mismo
Hotel. Así que el hotel tendrá que proteger sus habitaciones. Cómo, en un momento.
Míralo
El cliente
close() dice SALIR y cierra la conexión: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(); }}El servidor y el cliente en un solo programa:
Hotel hotel = new Hotel();hotel.add(new Room(101, "individual", 60));hotel.add(new Room(102, "doble", 85));hotel.add(new Room(201, "doble", 95));hotel.add(new Room(202, "suite", 140));HotelServer server = new HotelServer(5351, hotel);server.start();
HotelClient client = new HotelClient("localhost", 5351);System.out.println(client.send(Protocol.RESERVE, "102;Ana Torres"));System.out.println(client.send(Protocol.CHECK, "102"));System.out.println(client.send(Protocol.FREE));System.out.println(client.send(Protocol.CANCEL, "102;Ana Torres"));System.out.println(client.send(Protocol.CHECK, "305"));client.close();server.stop();OK:La habitación 102 es tuya, Ana Torres.OK:102, doble, 85 € por noche, ocupadaOK:101, individual, 60 € por noche, libre; 201, doble, 95 € por noche, libre; 202, suite, 140 € por noche, libreOK:La reserva de la habitación 102 está anulada.ERROR:No existe la habitación 305.La idea
Dos para una habitación
| Agencia A | Agencia B | |
|---|---|---|
| 1 | comprueba: la 102 está libre | |
| 2 | comprueba: la 102 está libre | |
| 3 | ocupa la 102 para su huésped | |
| 4 | ocupa la 102 para su huésped y anota a ese huésped |
Las dos reciben una confirmación. No hay ningún error en ninguna línea de código por separado. El error es que los pasos de las dos solicitudes se intercalan.
La solución: solo una solicitud a la vez entra en el hotel. Entonces «comprobar y ocupar» es atómico: nadie puede meterse entre la comprobación y la ocupación de la habitación. En Java lo hacesynchronized en cada método público de Hotel:public synchronized void reserve(int number, String guest) { if (guest.isBlank()) { throw new HotelException("El nombre del huésped es obligatorio."); } Room room = find(number); if (!room.isFree()) { throw new RoomTakenException("La habitación " + number + " ya está ocupada."); } room.occupy(); guests.put(number, guest);}public synchronized void reserve(int number, String guest) { if (guest.isBlank()) { throw new HotelException("El nombre del huésped es obligatorio."); } Room room = find(number); if (!room.isFree()) { throw new RoomTakenException("La habitación " + number + " ya está ocupada."); } room.occupy(); guests.put(number, guest);}Paso a paso, en palabras
- La habitación 102 está libre. Ana Torres y Bruno Silva la reservan en el mismo instante.
- Primero sin synchronized. Este es un orden posible: la solicitud de Ana comprueba y ve «libre».
- La solicitud de Bruno comprueba antes de que Ana haya ocupado la habitación: también ve «libre».
- Ana ocupa la habitación y anota su nombre.
- Bruno también ocupa la habitación y anota su nombre. Los dos tienen una confirmación para la misma habitación.
- Desde el principio, con synchronized: en el hotel entra solo un hilo a la vez.
- Digamos que Ana es la primera: toma el cerrojo. La comprobación y la ocupación son un solo paso, y nadie se mete entre ellas.
- Bruno llega al hotel y espera hasta que el cerrojo quede libre.
- Bruno tiene el cerrojo. Ahora la comprobación ve «ocupada».
- RoomTakenException. La recepción la devuelve como una línea de error, y Bruno puede pedir otra habitación.
- El programa de la lección cuenta las que tienen éxito: 1 por habitación. Quién fue primero cambia en cada ejecución.
La prueba: dos clientes reservan la 102 a la vez, y luego veinte agencias reservan la 201 a la vez. Se recogen las respuestas, y el programa imprime cuántas tuvieron éxito:
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, "individual", 60));hotel.add(new Room(102, "doble", 85));hotel.add(new Room(201, "doble", 95));hotel.add(new Room(202, "suite", 140));HotelServer server = new HotelServer(5352, hotel);server.start();
String[] two = { "Ana Torres", "Bruno Silva" };System.out.println("Dos para la habitación 102, con éxito: " + race(5352, 102, two));
String[] agencies = new String[20];for (int i = 0; i < agencies.length; i++) { agencies[i] = "Agencia " + (i + 1);}System.out.println("Veinte para la habitación 201, con éxito: " + race(5352, 201, agencies));
HotelClient desk = new HotelClient("localhost", 5352);System.out.println(desk.send(Protocol.FREE));desk.close();server.stop();Dos para la habitación 102, con éxito: 1Veinte para la habitación 201, con éxito: 1OK:101, individual, 60 € por noche, libre; 202, suite, 140 € por noche, libremain espera a todos con join y cuenta los que tuvieron éxito.Quién se quedó con la habitación cambia en cada ejecución, así que el programa no lo imprime. Cuántas tuvieron éxito es siempre lo mismo: una por habitación.
Más precisamente, para curiosos
- Sin el bloqueo, el programa casi siempre diría 1 de todos modos: la ventana entre la comprobación y la ocupación de la habitación es pequeña. Pero «casi siempre» significa que una vez entre miles de reservas llegan dos huéspedes a la habitación. Un error así no se atrapa ejecutando el programa, sino pensando: qué datos son compartidos y quién los cambia al mismo tiempo.
-
synchronizeden un método bloquea todo el objetoHotel. Mientras un hilo reserva la 102, otro espera incluso para la 201. Con cuatro habitaciones está bien. Con miles de habitaciones se bloquea por habitación, por ejemplosynchronized (room) { ... }. - En un sistema real las habitaciones están en una base de datos, y la protección ocurre allí: una transacción o una condición en la propia consulta (
UPDATE rooms SET free = false WHERE number = 102 AND free = true). Entonces se cumple incluso con varios servidores, no solo dentro de un programa.
Pruébalo
Bloqueado, pero no del todo
synchronized. La recepción llama primero a la comprobación y luego a la ocupación. Con muchas solicitudes a la vez, a veces dos personas siguen consiguiendo la misma habitación. ¿En qué línea está el error?Elige la línea con el error.
reserve, como en nuestro Hotel.Míralo
El hotel completo
Los escenarios de prueba del enunciado, esta vez por la red, con dos clientes conectados a la vez. Al final dos personas reservan la 201 en el mismo instante:
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, "individual", 60));hotel.add(new Room(102, "doble", 85));hotel.add(new Room(201, "doble", 95));hotel.add(new Room(202, "suite", 140));HotelServer server = new HotelServer(5353, hotel);server.start();
HotelClient anna = new HotelClient("localhost", 5353);HotelClient boris = new HotelClient("localhost", 5353);say("Ana", anna, Protocol.RESERVE, "102;Ana Torres");say("Bruno", boris, Protocol.RESERVE, "102;Bruno Silva");say("Bruno", boris, Protocol.CHECK, "102");say("Bruno", boris, Protocol.CANCEL, "102;Bruno Silva");say("Ana", anna, Protocol.CANCEL, "102;Ana Torres");say("Bruno", boris, Protocol.RESERVE, "102;Bruno Silva");say("Ana", anna, Protocol.CHECK, "305");anna.close();boris.close();
String[] two = { "Ana Torres", "Vera Gil" };System.out.println("Dos para la habitación 201 a la vez, con éxito: " + race(5353, 201, two));HotelClient desk = new HotelClient("localhost", 5353);System.out.println(desk.send(Protocol.FREE));desk.close();server.stop();Ana > RESERVAR:102;Ana TorresAna < OK:La habitación 102 es tuya, Ana Torres.Bruno > RESERVAR:102;Bruno SilvaBruno < ERROR:La habitación 102 ya está ocupada.Bruno > CONSULTAR:102Bruno < OK:102, doble, 85 € por noche, ocupadaBruno > ANULAR:102;Bruno SilvaBruno < ERROR:La habitación 102 está reservada por otro huésped.Ana > ANULAR:102;Ana TorresAna < OK:La reserva de la habitación 102 está anulada.Bruno > RESERVAR:102;Bruno SilvaBruno < OK:La habitación 102 es tuya, Bruno Silva.Ana > CONSULTAR:305Ana < ERROR:No existe la habitación 305.Dos para la habitación 201 a la vez, con éxito: 1OK:101, individual, 60 € por noche, libre; 202, suite, 140 € por noche, libreMás precisamente, para curiosos
El programa completo, de principio a fin:
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 + " € por noche, " + (free ? "libre" : "ocupada"); }}
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("El nombre del huésped es obligatorio."); } Room room = find(number); if (!room.isFree()) { throw new RoomTakenException("La habitación " + number + " ya está ocupada."); } room.occupy(); guests.put(number, guest); }
public synchronized void cancel(int number, String guest) { Room room = find(number); if (room.isFree()) { throw new HotelException("La habitación " + number + " no está reservada."); } if (!guests.get(number).equals(guest)) { throw new HotelException("La habitación " + number + " está reservada por otro huésped."); } room.release(); guests.remove(number); }
private Room find(int number) { for (Room room : rooms) { if (room.getNumber() == number) { return room; } } throw new RoomNotFoundException("No existe la habitación " + 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 = "LIBRES"; public static final String CHECK = "CONSULTAR"; public static final String RESERVE = "RESERVAR"; public static final String CANCEL = "ANULAR"; public static final String EXIT = "SALIR";
public static final String OK = "OK"; public static final String ERROR = "ERROR"; public static final String BYE = "ADIÓS";}
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("Comando desconocido " + 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 + ":La habitación " + number + " es tuya, " + parts[1] + "."; }
private String cancel(String text) { String[] parts = numberAndGuest(text); int number = number(parts[0]); hotel.cancel(number, parts[1]); return Protocol.OK + ":La reserva de la habitación " + number + " está anulada."; }
private static String[] numberAndGuest(String text) { String[] parts = text.split(";", 2); if (parts.length != 2) { throw new HotelException("Escribe número y nombre, por ejemplo «102;Ana Torres»."); } return parts; }
private static int number(String text) { try { return Integer.parseInt(text.trim()); } catch (NumberFormatException e) { throw new HotelException("El número de la habitación es un número entero."); } }
private static String join(List<Room> rooms) { if (rooms.isEmpty()) { return "No hay habitaciones libres."; } 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("Se cortó la conexión con el cliente: " + 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, "individual", 60)); hotel.add(new Room(102, "doble", 85)); hotel.add(new Room(201, "doble", 95)); hotel.add(new Room(202, "suite", 140)); HotelServer server = new HotelServer(5353, hotel); server.start();
HotelClient anna = new HotelClient("localhost", 5353); HotelClient boris = new HotelClient("localhost", 5353); say("Ana", anna, Protocol.RESERVE, "102;Ana Torres"); say("Bruno", boris, Protocol.RESERVE, "102;Bruno Silva"); say("Bruno", boris, Protocol.CHECK, "102"); say("Bruno", boris, Protocol.CANCEL, "102;Bruno Silva"); say("Ana", anna, Protocol.CANCEL, "102;Ana Torres"); say("Bruno", boris, Protocol.RESERVE, "102;Bruno Silva"); say("Ana", anna, Protocol.CHECK, "305"); anna.close(); boris.close();
String[] two = { "Ana Torres", "Vera Gil" }; System.out.println("Dos para la habitación 201 a la vez, con éxito: " + race(5353, 201, two)); HotelClient desk = new HotelClient("localhost", 5353); System.out.println(desk.send(Protocol.FREE)); desk.close(); server.stop(); }}Ejercicio
Sigue por tu cuenta
Trabaja con el programa completo de la tarjeta anterior.
1. Cambio de habitación. El huésped se muda de una habitación a otra con MOVER:102;202;Ana Torres. La respuesta es OK:Ana Torres está en la habitación 202. Si la habitación nueva está ocupada, el huésped se queda en la antigua. El cambio es un solo método en Hotel, synchronized: nadie debe ocupar la habitación nueva entre la liberación de la antigua y la ocupación de la nueva.
OK:La habitación 102 es tuya, Ana Torres.OK:La habitación 201 es tuya, Bruno Silva.ERROR:La habitación 201 ya está ocupada.OK:Ana Torres está en la habitación 202.OK:101, individual, 60 € por noche, libre; 102, doble, 85 € por noche, libreMás ideas
- Noches y total. Una reserva es para un número de noches, y la confirmación dice el total: «3 noches, 255 €».
- Fechas. Una habitación se reserva por días, por ejemplo del 14 al 16 de diciembre. Dos reservas de la misma habitación no deben solaparse. Si la habitación está libre depende de las fechas.
- Mis reservas.
MIAS:Ana Torresdice qué habitaciones son de este huésped. - Lista de espera. Si la habitación está ocupada, el huésped se apunta para esperar. Cuando se anula, pasa al primero de la lista.
-
Un cliente desde el teclado. Un segundo programa lee comandos del teclado con
Scannery los envía al servidor, que se ejecuta en otra terminal.
Test
Ponte a prueba
Lecciones relacionadas
Sección «Lecciones relacionadas»- Se basa en: Lambdas · Streams · Hilos · Programación en red
- Ejercicios sobre el tema: Proyecto