Requirements & System Scope
Functional Scope (In-Scope)
- Tables and Opening Hours: A restaurant owns tables with a seat capacity and opens at a fixed time and closes at a fixed time. A booking is only accepted when the dining time finishes before closing.
- Interval Reservations: A party books a start time. The table is blocked for a default dining duration of 90 minutes plus a 15 minute turnover buffer, expressed as one half-open interval.
- No Double Booking: A table never holds two reservations whose blocked intervals overlap, even when many guests book at the same moment.
- Table Allocation: A
TableAllocationStrategychooses the tables. The default best fit picks the smallest free table that seats the party and joins an adjacent pair of tables for a party that no single table can hold. - Cancellation and No-Show: A cancellation frees the tables immediately. A no-show is only accepted once the guest is 15 minutes late, and it frees the tables too.
- Waitlist: A party that cannot be seated can wait for its requested slot. Whenever a cancellation or no-show frees capacity, the first waiting party that now fits is promoted to a confirmed reservation.
- Notifications: Listeners observe confirmations, waitlisting, rejections, cancellations, no-shows and promotions.
Explicit Boundaries (Out-of-Scope)
- No Persistence or Payments: Storage is in memory. Deposits and cancellation fees are left as an extension.
- No Calendar or Wall Clock: Times are minutes since midnight for a single service day, and callers pass the current minute when they report a no-show. Requests for a time that has already passed are not rejected.
- Only Simple Table Joins: A table can be joined with at most one partner, so a party never spans three tables.
- One Dining Area: Zones such as patio and bar, and per-party dining durations, are not modelled.
Class Diagram & Entity Relationships
The Restaurant orchestrates booking, the waitlist and notifications, while each Table owns its own sorted reservations and its own lock. A Reservation knows every table it occupies, and that list is sorted by table id so every multi-table operation visits tables in the same order. Every class, field and method below mirrors the Java blueprint.
- Table as the unit of consistency: the sorted reservations and the lock live together inside
Table, so the overlap check and the insert can be made atomic without a restaurant-wide lock. - Reservation as the unit of atomicity: a booking that spans two joined tables is one
Reservationobject, soTable.bookAlleither places it on every table or on none. - Interfaces at the two seams:
TableAllocationStrategyvaries how tables are chosen andReservationListenervaries who hears about events, and neither change touchesRestaurant.
Design Patterns & SOLID Principles
- Strategy Pattern (Table Allocation):
Restaurantasks aTableAllocationStrategywhich tables to use and never decides itself.BestFitStrategyis the only implementation shipped, and a strategy that prefers window tables or rotates servers plugs in at construction without touching booking, cancellation or waitlist code. - Observer Pattern (Reservation Events):
Restaurant.emitpushesCONFIRMED,WAITLISTED,REJECTED,CANCELLED,NO_SHOWandPROMOTEDevents to every registeredReservationListener.ConsoleListenerprints them, and an SMS or email sender would be another listener. Events are emitted after the locks are released, so a slow listener never holds up a booking. - Value Object (TimeInterval):
TimeIntervalis immutable and owns the overlap test, soTableand the allocation code share one definition of a clash. - Fine-Grained Locking with Ordered Acquisition (Table.bookAll): Each
Tablehas its own lock, and a booking that spans two tables always locks them in table id order. This keeps unrelated bookings parallel and rules out deadlock. - Iterator Pattern (Waitlist Promotion): In the Java blueprint,
promoteFromWaitlistwalks the waitlist with an explicitIteratorand callsit.remove()on each party that gets a table, which afor eachloop cannot do safely in the middle of a traversal. - SOLID:
TimeIntervalonly reasons about time,Tableonly guards its own reservations andRestaurantonly orchestrates (single responsibility). New allocation rules and new listeners are added without editingRestaurant(open closed), andRestaurantdepends on the two interfaces rather than concrete classes (dependency inversion).
Algorithm: Interval Availability & Best-Fit Allocation
The overlap rule
Every booking blocks its table for the half-open interval [start, start + dining + turnover). Two intervals clash exactly when a.start < b.end && b.start < a.end. Because the end is exclusive, a guest who arrives the minute a previous blocked interval ends is allowed, which is why Alice at [19:00-20:45) and Dave at [20:45-22:30) share table T1 in the demo. The turnover buffer lives inside the blocked interval, so cleaning time is never double sold.
Baseline: scan every table against every reservation
The simplest availability check loops over all tables, and for each table loops over all of its reservations calling overlaps. With T tables and R reservations per table that costs O(T Γ R) per request, and a best-fit choice also has to sort the tables by seats first. That is fine for a demo and slow for a busy Saturday night with hundreds of reservations on the books.
Optimization: a sorted structure per table (the aha moment)
Reservations on one table never overlap, so ordering them by start also orders them by end. That means a new interval [s, e) can only clash with the last reservation that starts at or before s, or with the first reservation that starts after s. Everything earlier ends before that predecessor starts, and everything later starts after that successor starts. Two neighbour lookups decide availability, which is O(log n) for the n reservations on that table. Java keeps them in a TreeMap and uses floorEntry and higherEntry. TypeScript and Python keep a sorted array and a binary search (bisect_right in Python), where the search is O(log n) but inserting into the array shifts elements, so a production Python or TypeScript service would use a balanced tree or a database index instead.
Best fit by walking tables in ascending capacity
Restaurant.addTable keeps the table list sorted by seats and then by id, so BestFitStrategy simply walks it once and returns the first table that has enough seats and is free for the slot. That first hit is the smallest table that works, which saves large tables for large parties. Only when no single table fits does the strategy scan the adjacent pairs and pick the free pair with the fewest total seats. A request costs O(T log n) in the worst case, because every table with enough seats may need one availability check before the first free one is found.
- Availability of one table:
O(log n)search for the neighbours. - Choose tables for one request:
O(T log n)worst case, because the single table pass and the pair pass each make a constant number of checks per table. - Book on one table or a pair:
O(log n)for the checks and the insert in Java, plus acquiring one or two locks. - Waitlist promotion after a cancellation:
O(W Γ T log n)forWwaiting parties, because each one is retried against the tables once.
Best fit is a greedy choice per request, not an optimal packing of the whole evening. It compares seat counts only and ignores the gaps in a tableβs timeline. A 19:00 booking placed on a table that already has a 21:00 booking leaves a 15 minute hole nobody can use, while an empty table of the same size would have kept a clean evening. Scoring candidates by leftover gap is the usual follow-up, and naming this limit is a strong interview signal.
Core Execution Workflows
1. Reserve a table
- The caller invokes
reserve(guest, partySize, startMinute). A party size of zero or less throws an error. slotForrejects the request with aREJECTEDevent when the start is before opening or the dining time would run past closing, or when the party is larger than the biggest single table or joined pair. It returnsnullin both cases.- Otherwise it builds the blocked interval, which is the start plus 90 minutes of dining plus the 15 minute turnover buffer.
tryReserveasksstrategy.choosefor tables. In Java and Python eachisFreecall takes that tableβs lock only for the duration of the check, so the answer is advisory. An empty answer means nothing fits, soreservereturnsnullwith aREJECTEDevent, whilereserveOrWaitcontinues with workflow 2.- A
Reservationis created with the chosen tables, sorted by id, andTable.bookAlllocks all of them in that order and checks every table again.- If every table is still free, the reservation is inserted into all of them, the locks are released in reverse order and the reservation is stored by id.
- If another guest took a chosen table in the meantime, nothing is inserted anywhere and
tryReservegoes back tochoosewith fresh data. TypeScript runs choose and book in one synchronous call, so this retry cannot trigger there.
- A
CONFIRMEDevent is emitted after all locks are released.
2. Reserve or join the waitlist
reserveOrWaitruns the same validation and a firsttryReserve.- When that fails, it takes
waitlistLockand tries once more, because a cancellation may have freed a table between the first try and now. - If the second try also fails, a
WaitlistEntryis appended and aWAITLISTEDevent follows. A party that no table or pair can ever seat is rejected up front instead of waiting forever.
3. Cancel a reservation
cancellooks up the reservation and callstransition(CONFIRMED, CANCELLED). An unknown id, or a reservation that is already cancelled or marked no-show, returnsfalseand changes nothing.Table.releaseAllremoves the reservation from every table it held, again locking in id order.- A
CANCELLEDevent is emitted and the waitlist is scanned for promotions.
4. Mark a no-show
markNoShow(id, nowMinute)refuses untilnowMinuteis at least the start plus the 15 minute grace period, and returnsfalse.- After the grace period it applies
transition(CONFIRMED, NO_SHOW), releases the whole blocked interval, emitsNO_SHOWand scans the waitlist.
5. Promote from the waitlist
- Under
waitlistLock, the entries are visited in arrival order and each one is retried for its requested slot withtryReserve. - An entry that fits is removed and becomes a confirmed reservation. An entry that still does not fit stays in its place, so a later, smaller party can be seated ahead of an earlier large one.
- After the lock is released, one
PROMOTEDevent is emitted per promoted party. In the demo, cancelling Alice frees T1, Frankβs party of four does not fit, and Ginaβs party of two is promoted. Cancelling Carol later frees T3 and promotes Frank.
Concurrency & Thread Safety Strategy
Shared state and the races
The mutable state is each tableβs sorted reservations, the reservation index, the waitlist, each reservationβs status, the table list and the id counter. Several races follow from that.
- Two guests, one last table: both call
isFreefor the same slot, both see true, and both insert. The result is two overlapping reservations on one table. This is a classic check-then-act race. - Half-made pair booking: a party of six needs T4 and T5. If the code inserted into T4 and then found T5 taken, a reservation would sit on one table only.
- Deadlock on two tables: one thread locks T4 then T5 while another locks T5 then T4, and both wait forever.
- Double cancel or cancel against no-show: two callers both see the reservation as confirmed and both release it and promote the waitlist.
- Lost wakeup on the waitlist: a guest fails to book, a cancellation frees the table and scans an empty waitlist, and only then does the guest queue up and wait for nothing.
The guards and where they sit
In Java every Table has a ReentrantLock. Table.bookAll locks all the reservationβs tables, re-runs isFreeLocked on each, and only then inserts into all of them, so the overlap check and the insert are one atomic step per table and a failed check leaves nothing behind. The earlier isFree calls inside the strategy are only a hint and can be stale, which is why tryReserve loops back to choose when bookAll loses a race. Each retry means another booking succeeded, so the loop makes progress. Lock order comes from Reservation, which sorts its tables by id once, and both bookAll and releaseAll iterate that list, so no two threads can wait on each other in a cycle. This is the global lock ordering fix described on the Deadlock Prevention and Lock Ordering page.
Reservation.transition is a synchronized compare-and-set, so only one of two racing cancels moves the status away from CONFIRMED and the loser returns false without touching a table. reserveOrWait retries once while holding waitlistLock, and cancel and markNoShow release tables first and take waitlistLock afterwards to promote. Either the retry sees the freed table or the promotion sees the queued party, so nobody is stranded. The lock hierarchy is waitlistLock first and table locks second, never the reverse, and listeners run with no lock held. The reservation index is a ConcurrentHashMap, the table and listener lists are CopyOnWriteArrayList instances, and ids come from an AtomicInteger.
Python uses the same shape with a threading.Lock per table acquired through ExitStack in id order, a lock inside Reservation for the status change, a waitlist lock, a lock around the id counter and a copy-on-write table list. Single dictionary reads and writes on the reservation index are atomic under CPythonβs global interpreter lock. TypeScript has no locks because it runs on one thread. bookAll and promoteFromWaitlist contain no await, so each call runs to completion before any other booking starts. That stops being true the moment the table storage becomes asynchronous, and then each table needs a mutex or the database has to enforce the rule.
What the blueprint does not guard
A plain reserve can reject a guest spuriously when a cancellation lands just after choose returned an empty list, which is why reserveOrWait does its second look under the waitlist lock. A cancelled reservation is marked CANCELLED a moment before its tables are released, so a competitor may see the table busy slightly longer than necessary, which is safe but not instant. Promotion holds waitlistLock while it takes table locks, so cancellations promote one at a time. Most importantly, all of this is in one process. Two server instances would each keep their own tables and happily double book.
In production the database is the arbiter. In PostgreSQL a table holding one row per reserved table, with a tstzrange column for the blocked interval, can carry an exclusion constraint such as EXCLUDE USING gist (table_id WITH =, blocked WITH &&), which needs the btree_gist extension. An overlapping insert fails with an exclusion violation, and the service catches it and tries the next candidate table. A pair booking inserts both rows in one transaction in table id order, so a violation on the second row rolls back the first and no half-made reservation survives. Add an idempotency key on the booking request so a client retry does not create a second reservation.
A test that exposes a broken guard
Release many threads together on a restaurant with one table and one slot and assert that exactly one booking succeeds, which is what the demoβs eight-guest race prints. Then run threads that mix single-table and pair bookings, cancellations and no-shows for a few seconds, and afterwards check that every tableβs reservations are sorted and pairwise disjoint and that all threads joined within a timeout. Removing the recheck in bookAll produces overlapping reservations, and with a custom strategy that returns joined pairs in varying order, locking tables in that order instead of id order can hang the threads. In Python, lower sys.setswitchinterval so the scheduler switches threads often enough to hit the race.
Complete Clean Code Blueprint
The blueprint below implements the same design in Java, TypeScript and Python. Each version books on sorted per-table timelines, picks the best fitting table or joined pair, promotes the waitlist and ends with a driver that prints a fixed scenario, including eight guests racing for one table.
// βββ JAVA BLUEPRINT ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
// Half-open interval [start, end) in minutes since midnight.
final class TimeInterval {
private final int start;
private final int end;
TimeInterval(int start, int end) {
if (start < 0 || start >= end) {
throw new IllegalArgumentException("Need 0 <= start < end.");
}
this.start = start;
this.end = end;
}
int getStart() { return start; }
int getEnd() { return end; }
// Back-to-back intervals do not overlap because the end is exclusive.
boolean overlaps(TimeInterval other) {
return start < other.end && other.start < end;
}
static String clock(int minute) {
return String.format("%02d:%02d", minute / 60, minute % 60);
}
@Override
public String toString() {
return "[" + clock(start) + "-" + clock(end) + ")";
}
}
enum ReservationStatus { CONFIRMED, CANCELLED, NO_SHOW }
class Reservation {
private final String id;
private final String guest;
private final int partySize;
private final TimeInterval interval;
private final List<Table> tables;
private ReservationStatus status = ReservationStatus.CONFIRMED;
Reservation(String id, String guest, int partySize, TimeInterval interval, List<Table> tables) {
this.id = id;
this.guest = guest;
this.partySize = partySize;
this.interval = interval;
// Sorted by table id once, so every multi-table lock acquisition uses the same order.
List<Table> ordered = new ArrayList<>(tables);
ordered.sort(Comparator.comparing(Table::getId));
this.tables = Collections.unmodifiableList(ordered);
}
String getId() { return id; }
String getGuest() { return guest; }
int getPartySize() { return partySize; }
TimeInterval getInterval() { return interval; }
List<Table> getTables() { return tables; }
synchronized ReservationStatus getStatus() { return status; }
// Atomic compare-and-set so only one of two racing cancels wins.
synchronized boolean transition(ReservationStatus from, ReservationStatus to) {
if (status != from) return false;
status = to;
return true;
}
String tableNames() {
StringBuilder names = new StringBuilder();
for (Table table : tables) {
if (names.length() > 0) names.append("+");
names.append(table.getId());
}
return names.toString();
}
}
class Table {
private final String id;
private final int capacity;
// Reservations never overlap, so sorting by start also sorts by end.
private final TreeMap<Integer, Reservation> byStart = new TreeMap<>();
private final ReentrantLock lock = new ReentrantLock();
private volatile Table adjacent;
Table(String id, int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("Capacity must be positive.");
}
this.id = id;
this.capacity = capacity;
}
String getId() { return id; }
int getCapacity() { return capacity; }
Table getAdjacent() { return adjacent; }
// Two tables that can be pushed together to seat a large party.
void joinWith(Table other) {
this.adjacent = other;
other.adjacent = this;
}
boolean isFree(TimeInterval slot) {
lock.lock();
try {
return isFreeLocked(slot);
} finally {
lock.unlock();
}
}
// O(log n): only the neighbour at or before the start and the one after it can overlap.
private boolean isFreeLocked(TimeInterval slot) {
Map.Entry<Integer, Reservation> before = byStart.floorEntry(slot.getStart());
if (before != null && before.getValue().getInterval().overlaps(slot)) return false;
Map.Entry<Integer, Reservation> after = byStart.higherEntry(slot.getStart());
return after == null || !after.getValue().getInterval().overlaps(slot);
}
// Locks every table in id order, checks all of them, then inserts into all or none.
static boolean bookAll(Reservation reservation) {
List<Table> ordered = reservation.getTables();
for (Table table : ordered) table.lock.lock();
try {
for (Table table : ordered) {
if (!table.isFreeLocked(reservation.getInterval())) return false;
}
for (Table table : ordered) {
table.byStart.put(reservation.getInterval().getStart(), reservation);
}
return true;
} finally {
for (int i = ordered.size() - 1; i >= 0; i--) ordered.get(i).lock.unlock();
}
}
static void releaseAll(Reservation reservation) {
List<Table> ordered = reservation.getTables();
for (Table table : ordered) table.lock.lock();
try {
for (Table table : ordered) {
table.byStart.remove(reservation.getInterval().getStart(), reservation);
}
} finally {
for (int i = ordered.size() - 1; i >= 0; i--) ordered.get(i).lock.unlock();
}
}
}
interface TableAllocationStrategy {
// The tables arrive sorted by seats ascending. Returns the tables to use, or an empty list.
List<Table> choose(List<Table> tablesBySeats, int partySize, TimeInterval slot);
}
class BestFitStrategy implements TableAllocationStrategy {
@Override
public List<Table> choose(List<Table> tablesBySeats, int partySize, TimeInterval slot) {
for (Table table : tablesBySeats) {
if (table.getCapacity() >= partySize && table.isFree(slot)) {
return List.of(table);
}
}
// No single table works, so look for the smallest free adjacent pair that seats the party.
List<Table> best = List.of();
int bestSeats = Integer.MAX_VALUE;
for (Table table : tablesBySeats) {
Table partner = table.getAdjacent();
if (partner == null) continue;
int seats = table.getCapacity() + partner.getCapacity();
if (seats >= partySize && seats < bestSeats && table.isFree(slot) && partner.isFree(slot)) {
best = List.of(table, partner);
bestSeats = seats;
}
}
return best;
}
}
interface ReservationListener {
void onEvent(String event, String message);
}
class ConsoleListener implements ReservationListener {
@Override
public void onEvent(String event, String message) {
System.out.println("[" + event + "] " + message);
}
}
class WaitlistEntry {
private final String guest;
private final int partySize;
private final int startMinute;
WaitlistEntry(String guest, int partySize, int startMinute) {
this.guest = guest;
this.partySize = partySize;
this.startMinute = startMinute;
}
String getGuest() { return guest; }
int getPartySize() { return partySize; }
int getStartMinute() { return startMinute; }
}
class Restaurant {
static final int NO_SHOW_GRACE_MINUTES = 15;
private final int openMinute;
private final int closeMinute;
private final int diningMinutes;
private final int turnoverMinutes;
private final TableAllocationStrategy strategy;
private final List<Table> tables = new CopyOnWriteArrayList<>();
private final Map<String, Reservation> reservations = new ConcurrentHashMap<>();
private final List<WaitlistEntry> waitlist = new ArrayList<>();
private final Object waitlistLock = new Object();
private final List<ReservationListener> listeners = new CopyOnWriteArrayList<>();
private final AtomicInteger sequence = new AtomicInteger(1);
Restaurant(int openMinute, int closeMinute, int diningMinutes, int turnoverMinutes, TableAllocationStrategy strategy) {
if (openMinute >= closeMinute || diningMinutes <= 0 || turnoverMinutes < 0) {
throw new IllegalArgumentException("Invalid opening hours or durations.");
}
this.openMinute = openMinute;
this.closeMinute = closeMinute;
this.diningMinutes = diningMinutes;
this.turnoverMinutes = turnoverMinutes;
this.strategy = Objects.requireNonNull(strategy);
}
synchronized void addTable(Table table) {
for (Table existing : tables) {
if (existing.getId().equals(table.getId())) {
throw new IllegalArgumentException("Duplicate table " + table.getId());
}
}
tables.add(table);
tables.sort(Comparator.comparingInt(Table::getCapacity).thenComparing(Table::getId));
}
void addListener(ReservationListener listener) {
listeners.add(listener);
}
int waitlistSize() {
synchronized (waitlistLock) {
return waitlist.size();
}
}
// Books a table now or returns null. Never queues the party.
Reservation reserve(String guest, int partySize, int startMinute) {
TimeInterval slot = slotFor(guest, partySize, startMinute);
if (slot == null) return null;
Reservation reservation = tryReserve(guest, partySize, slot);
if (reservation == null) {
emit("REJECTED", guest + " party of " + partySize + " at " + TimeInterval.clock(startMinute) + ": no table free");
} else {
emit("CONFIRMED", describe(reservation));
}
return reservation;
}
// Books a table now, otherwise joins the waitlist and returns null.
Reservation reserveOrWait(String guest, int partySize, int startMinute) {
TimeInterval slot = slotFor(guest, partySize, startMinute);
if (slot == null) return null;
Reservation reservation = tryReserve(guest, partySize, slot);
boolean queued = false;
if (reservation == null) {
synchronized (waitlistLock) {
// A cancellation may have freed a table since the first try, so look again before queuing.
reservation = tryReserve(guest, partySize, slot);
if (reservation == null) {
waitlist.add(new WaitlistEntry(guest, partySize, startMinute));
queued = true;
}
}
}
if (reservation != null) {
emit("CONFIRMED", describe(reservation));
} else if (queued) {
emit("WAITLISTED", guest + " party of " + partySize + " wants " + TimeInterval.clock(startMinute));
}
return reservation;
}
boolean cancel(String reservationId) {
Reservation reservation = reservations.get(reservationId);
if (reservation == null || !reservation.transition(ReservationStatus.CONFIRMED, ReservationStatus.CANCELLED)) {
return false;
}
Table.releaseAll(reservation);
emit("CANCELLED", reservation.getGuest() + " party of " + reservation.getPartySize()
+ " released " + reservation.tableNames() + " " + reservation.getInterval());
promoteFromWaitlist();
return true;
}
// Accepted only once the guest is NO_SHOW_GRACE_MINUTES late. The whole block is released.
boolean markNoShow(String reservationId, int nowMinute) {
Reservation reservation = reservations.get(reservationId);
if (reservation == null) return false;
if (nowMinute < reservation.getInterval().getStart() + NO_SHOW_GRACE_MINUTES) return false;
if (!reservation.transition(ReservationStatus.CONFIRMED, ReservationStatus.NO_SHOW)) return false;
Table.releaseAll(reservation);
emit("NO_SHOW", reservation.getGuest() + " never arrived, released " + reservation.tableNames());
promoteFromWaitlist();
return true;
}
private TimeInterval slotFor(String guest, int partySize, int startMinute) {
if (partySize <= 0) {
throw new IllegalArgumentException("Party size must be positive.");
}
if (startMinute < openMinute || startMinute + diningMinutes > closeMinute) {
emit("REJECTED", guest + " at " + TimeInterval.clock(startMinute) + ": dining must finish by "
+ TimeInterval.clock(closeMinute));
return null;
}
if (partySize > largestSeating()) {
emit("REJECTED", guest + " party of " + partySize + ": no table or joined pair seats that many");
return null;
}
// The table stays blocked for the meal plus the turnover buffer.
return new TimeInterval(startMinute, startMinute + diningMinutes + turnoverMinutes);
}
private int largestSeating() {
int best = 0;
for (Table table : tables) {
best = Math.max(best, table.getCapacity());
Table partner = table.getAdjacent();
if (partner != null) best = Math.max(best, table.getCapacity() + partner.getCapacity());
}
return best;
}
private Reservation tryReserve(String guest, int partySize, TimeInterval slot) {
while (true) {
List<Table> chosen = strategy.choose(tables, partySize, slot);
if (chosen.isEmpty()) return null;
Reservation reservation = new Reservation("R-" + sequence.getAndIncrement(), guest, partySize, slot, chosen);
if (Table.bookAll(reservation)) {
reservations.put(reservation.getId(), reservation);
return reservation;
}
// Someone booked a chosen table between choose() and bookAll(). Choose again.
}
}
private void promoteFromWaitlist() {
List<Reservation> promoted = new ArrayList<>();
synchronized (waitlistLock) {
Iterator<WaitlistEntry> it = waitlist.iterator();
while (it.hasNext()) {
WaitlistEntry entry = it.next();
TimeInterval slot = new TimeInterval(entry.getStartMinute(), entry.getStartMinute() + diningMinutes + turnoverMinutes);
Reservation reservation = tryReserve(entry.getGuest(), entry.getPartySize(), slot);
if (reservation != null) {
it.remove();
promoted.add(reservation);
}
}
}
for (Reservation reservation : promoted) {
emit("PROMOTED", describe(reservation) + " from the waitlist");
}
}
private String describe(Reservation r) {
return r.getGuest() + " party of " + r.getPartySize() + " booked " + r.tableNames() + " " + r.getInterval();
}
private void emit(String event, String message) {
for (ReservationListener listener : listeners) listener.onEvent(event, message);
}
}
public class Main {
static Restaurant newRestaurant() {
// Open 17:00 to 23:00. A booking blocks 90 minutes of dining plus a 15 minute turnover buffer.
return new Restaurant(17 * 60, 23 * 60, 90, 15, new BestFitStrategy());
}
public static void main(String[] args) throws InterruptedException {
Restaurant bistro = newRestaurant();
bistro.addListener(new ConsoleListener());
Table t4 = new Table("T4", 4);
Table t5 = new Table("T5", 4);
t4.joinWith(t5);
bistro.addTable(new Table("T1", 2));
bistro.addTable(new Table("T2", 2));
bistro.addTable(new Table("T3", 4));
bistro.addTable(t4);
bistro.addTable(t5);
System.out.println("--- Best fit, back-to-back booking and a joined pair ---");
Reservation alice = bistro.reserve("Alice", 2, 19 * 60);
Reservation bob = bistro.reserve("Bob", 2, 19 * 60);
Reservation carol = bistro.reserve("Carol", 3, 19 * 60 + 30);
bistro.reserve("Dave", 2, 20 * 60 + 45);
bistro.reserve("Erin", 6, 19 * 60);
System.out.println("--- Waitlist and rejections ---");
bistro.reserveOrWait("Frank", 4, 19 * 60);
bistro.reserveOrWait("Gina", 2, 19 * 60);
bistro.reserveOrWait("Ivy", 9, 19 * 60);
bistro.reserve("Hank", 2, 22 * 60);
System.out.println("--- A cancellation promotes the first party that fits ---");
bistro.cancel(alice.getId());
System.out.println("Cancel Alice again: " + bistro.cancel(alice.getId()));
System.out.println("--- No-show handling ---");
System.out.println("No-show at 19:10 accepted: " + bistro.markNoShow(bob.getId(), 19 * 60 + 10));
System.out.println("No-show at 19:15 accepted: " + bistro.markNoShow(bob.getId(), 19 * 60 + 15));
System.out.println("Waitlist size: " + bistro.waitlistSize());
bistro.cancel(carol.getId());
System.out.println("Waitlist size: " + bistro.waitlistSize());
System.out.println("--- Eight guests race for the last table ---");
Restaurant tiny = newRestaurant();
tiny.addTable(new Table("T1", 2));
int attempts = 8;
ExecutorService pool = Executors.newFixedThreadPool(attempts);
CountDownLatch gate = new CountDownLatch(1);
AtomicInteger booked = new AtomicInteger();
for (int i = 0; i < attempts; i++) {
final String guest = "Guest-" + i;
pool.submit(() -> {
try {
gate.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
if (tiny.reserve(guest, 2, 19 * 60) != null) booked.incrementAndGet();
});
}
gate.countDown();
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println(attempts + " attempts, " + booked.get() + " booked");
}
}Review
How helpful was this walkthrough?
Click a star to rate. We actively use this feedback to refine and update our system design content.
Discussion
Share your thoughts, ask questions, or help others.