Add food-delivery module: order state table, FIFO dispatcher, nearest / rated / longest-idle rider strategies, atomic stock and kitchen capacity, idempotent placing, seeded simulation (13 test classes, 19 transcripts)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b5BMpRV6przXHwuKTz
This commit is contained in:
Ankur Mhatre
2026-11-22 18:43:31 +05:30
co-authored by Claude Sonnet 5.5
parent 76012dd8c3
commit 3336e2ba15
68 changed files with 2323 additions and 0 deletions
+1
View File
@@ -29,6 +29,7 @@ One module per article. This repository currently holds:
| [`graph-algorithms`](graph-algorithms/) | Graph Algorithms in Java: Dijkstra, Topological Sort and Union-Find | this commit |
| [`elevator`](elevator/) | Low-Level Design: Elevator System in Java (State Pattern and Scheduling) | this commit |
| [`experienced-2-3y`](experienced-2-3y/) | Java Interview Questions for 2 to 3 Years Experience (Scenario-Based, with Answers) | this commit |
| [`food-delivery`](food-delivery/) | Low-Level Design: Food Delivery App (Zomato/Swiggy-Style) in Java | this commit |
## `collections` module
+70
View File
@@ -0,0 +1,70 @@
# food-delivery
Companion code for the ankurm.com article **Low-Level Design: Food Delivery App (Zomato/Swiggy-Style) in Java**.
The core of an order-to-door system in plain Java: an order lifecycle as a state table, restaurant search with two rankings, bills in exact
paise, three rider-assignment strategies behind one interface, a dispatcher with a first-in-first-out waiting queue, atomic stock and kitchen
capacity, idempotent placing, and a seeded minute-by-minute simulation that compares the strategies on identical demand. Every figure and
console line in the article is quoted from a file in `output/`, which the JUnit tests write while asserting the same numbers. There is no
`docs/` folder: the explanations live in the article itself.
## Versions
| Component | Version | Verified against |
|---|---|---|
| JDK | Temurin 25.0.5.1+2 (LTS) | `java -version` |
| JUnit | 6.1.3 | `junit-bom` `maven-metadata.xml` on Maven Central (latest GA; 6.2.0-M1 is a milestone) |
| Maven | 3.9.11 | `mvn -version` |
| maven-surefire-plugin | 3.6.1 | `maven-metadata.xml` on Maven Central (latest GA) |
No frameworks and no runtime dependencies: everything in `src/main` is plain Java.
## Quickstart
```bash
cd food-delivery
export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH"
./scripts/run-all.sh # runs every test and regenerates output/*.txt
```
The first Maven run must be online so the plugins land in the local cache. Three transcripts contain figures that depend on thread timing
(`09-stock-race.txt`, `10-partner-claim.txt`, `11b-reject-vs-cancel.txt`); they say so in their first lines and can differ from run to run.
Every other transcript is identical on every run.
## The pieces
| Class | Role |
|---|---|
| `OrderStatus` | the whole lifecycle as one table: eight legal moves out of sixty-four |
| `Order` | the only place a status changes; every mutator is synchronized, so a race on one order has one winner |
| `FoodDeliveryService` | the facade: search, place, accept, reject, prepare, ready, pick up, deliver, cancel |
| `Restaurant` | menu, rating, location and a kitchen capacity taken with a compare-and-set loop |
| `DeliveryPartner` | a rider whose claim is one `compareAndSet(AVAILABLE, BUSY)` |
| `PartnerAssignmentStrategy` | picks one rider from a list; `NearestPartner`, `RatedWithinRadius`, `LongestIdle` |
| `Dispatcher` | matches accepted orders to riders; orders with no rider wait in a FIFO queue |
| `StockLedger`, `Inventory` | all-or-nothing reservation of limited portions under one lock per restaurant |
| `PricingPolicy`, `StandardPricing` | subtotal, distance fee, free-delivery threshold, 5% tax rounded half up |
| `RestaurantRanking` | `NEAREST` and `TOP_RATED`, both ending in the id so ties never swap |
| `OrderListener`, `OrderEvent` | Observer: every status change and rider assignment is published |
| `Simulation` | seeded city and demand; runs a strategy to the last delivery |
| `FoodDeliveryException` | sealed family of business-rule failures |
The tests also hold two deliberately wrong versions, `NaiveInventory` and a naive rider claim, so the failures can be reproduced.
## Transcripts
| File | Written by | What it shows |
|---|---|---|
| `01-happy-path.txt` | `LifecycleTest` | one order from placed to delivered: bill, rider, event log |
| `02-state-machine.txt`, `02b-illegal-moves.txt`, `02c-no-partner.txt` | `StateMachineTest` | the 8x8 table, exact messages for illegal moves, pick-up without a rider |
| `03-pricing.txt` | `PricingTest` | delivery fee by distance, free delivery, half-up tax |
| `04-validation.txt` | `ValidationTest` | ten bad requests with exact messages, stock untouched |
| `05-search.txt` | `SearchTest` | the same restaurants ranked two ways |
| `06-assignment.txt`, `06b-radius-fallback.txt` | `AssignmentTest` | one order, three strategies, three riders |
| `07-dispatch-queue.txt`, `07b-cancel-while-waiting.txt` | `DispatchQueueTest` | the waiting queue and what frees it |
| `08-cancel-reject.txt` | `CancelRejectTest` | stock, kitchen slot and rider all come back |
| `09-stock-race.txt` | `StockRaceTest` | 16 buyers, 10 portions: naive versus locked |
| `10-partner-claim.txt`, `10b-dispatch-under-load.txt` | `PartnerClaimTest` | naive versus compare-and-set; 200 orders, 20 riders, 8 threads |
| `11-accept-capacity.txt`, `11b-reject-vs-cancel.txt` | `AcceptRaceTest` | capacity holds; reject versus cancel has one winner |
| `12-idempotency.txt` | `IdempotencyTest` | a double tap and 16 racing retries create one order |
| `13-simulation.txt` | `SimulationTest` | three strategies at three load levels on identical orders |
+16
View File
@@ -0,0 +1,16 @@
One order, from placed to delivered
===================================
Meera (4,4) orders from Biryani House (2,3), 3 km away
food Rs 547.00 + delivery Rs 44.00 + tax Rs 27.35 = Rs 618.35
Event log
t=00 O-0001 - -> PLACED
t=02 O-0001 PLACED -> ACCEPTED
t=02 O-0001 partner P1 assigned
t=03 O-0001 ACCEPTED -> PREPARING
t=14 O-0001 PREPARING -> READY
t=15 O-0001 READY -> PICKED_UP
t=21 O-0001 PICKED_UP -> DELIVERED
After delivery: Imran is AVAILABLE at (4,4), idle since minute 21, deliveries 1
+14
View File
@@ -0,0 +1,14 @@
Order state machine: which of the 64 moves are legal
====================================================
from \ to PLA ACC PRE REA PIC DEL REJ CAN
PLACED . yes . . . . yes yes
ACCEPTED . . yes . . . . yes
PREPARING . . . yes . . . .
READY . . . . yes . . .
PICKED_UP . . . . . yes . .
DELIVERED . . . . . . . .
REJECTED . . . . . . . .
CANCELLED . . . . . . . .
legal moves: 8 of 64
@@ -0,0 +1,9 @@
Illegal moves: the exact message, and the status afterwards
===========================================================
PLACED, markReady : O-0001 cannot move from PLACED to READY; allowed from PLACED: [ACCEPTED, REJECTED, CANCELLED]
status afterwards : PLACED
PREPARING, cancel : O-0001 cannot move from PREPARING to CANCELLED; allowed from PREPARING: [READY]
DELIVERED, cancel : O-0001 cannot move from DELIVERED to CANCELLED; allowed from DELIVERED: []
+6
View File
@@ -0,0 +1,6 @@
READY to PICKED_UP is legal on paper, but not without a rider
=============================================================
all riders offline, order READY
pickUp: O-0001 has no delivery partner yet, so it cannot be picked up
status afterwards: READY
+9
View File
@@ -0,0 +1,9 @@
Bills: delivery by distance, free delivery from Rs 599, tax rounded half up
===========================================================================
food Rs 99.00 6 km -> food Rs 99.00 + delivery Rs 68.00 + tax Rs 4.95 = Rs 171.95
food Rs 547.00 3 km -> food Rs 547.00 + delivery Rs 44.00 + tax Rs 27.35 = Rs 618.35
food Rs 599.00 12 km -> food Rs 599.00 + delivery Rs 0.00 + tax Rs 29.95 = Rs 628.95
food Rs 598.99 12 km -> food Rs 598.99 + delivery Rs 116.00 + tax Rs 29.95 = Rs 744.94
food Rs 100.10 1 km -> food Rs 100.10 + delivery Rs 28.00 + tax Rs 5.01 = Rs 133.11
food Rs 100.30 1 km -> food Rs 100.30 + delivery Rs 28.00 + tax Rs 5.02 = Rs 133.32
+15
View File
@@ -0,0 +1,15 @@
Bad requests: the exact message for each, and the stock afterwards
==================================================================
blank key InvalidOrder: an idempotency key is required
unknown customer NotFound: customer C9 not found
unknown restaurant NotFound: restaurant R9 not found
empty cart InvalidOrder: the cart is empty
item from another menu InvalidOrder: Biryani House has no item p1
quantity zero InvalidOrder: quantity for Chicken Biryani must be 1 to 20, got 0
quantity 21 InvalidOrder: quantity for Chicken Biryani must be 1 to 20, got 21
24 km away InvalidOrder: Pizza Point is 24 km away; we deliver up to 15 km
more than the stock OutOfStock: b1: wanted 6, only 5 left
closed restaurant Dosa Corner is closed
two-line cart where the second line is short: Veg Biryani stock still 3
+20
View File
@@ -0,0 +1,20 @@
Search from Meera at (4,4): nearest first versus top rated first
================================================================
blank query, 10 km, NEAREST
Biryani House 3 km rating 4.4
Dosa Corner 6 km rating 4.6
Pizza Point 6 km rating 4.1
Burger Lab 6 km rating 3.9
blank query, 10 km, TOP_RATED
Dosa Corner 6 km rating 4.6
Biryani House 3 km rating 4.4
Pizza Point 6 km rating 4.1
Burger Lab 6 km rating 3.9
query "burger"
Burger Lab: [Chicken Burger, Veg Burger]
radius 4 km: [Biryani House]
radius 4 km after Biryani House closes: 0 results
+12
View File
@@ -0,0 +1,12 @@
Same order, same three free riders, three strategies
====================================================
Order pickup: Biryani House (2,3)
P1 Imran at (3,3) 1 km away rating 4.2 idle since minute 30
P2 Kavya at (6,2) 5 km away rating 4.8 idle since minute 20
P3 Sunil at (2,6) 3 km away rating 4.5 idle since minute 10
nearest -> P1
rated<=5km -> P2 (all three are within 5 km, so the best rating wins)
rated<=2km -> P1 (only P1 is within 2 km)
longest-idle -> P3 (P3 has waited longest)
@@ -0,0 +1,4 @@
rated<=0km: nobody is that close, so it falls back to the nearest
=================================================================
assigned: P1
@@ -0,0 +1,17 @@
One rider, three orders: the queue and what frees it
====================================================
three orders accepted, one rider (P1) online
O-0001 rider P1
O-0002 rider null
O-0003 rider null
waiting: [O-0002, O-0003]
O-0001 delivered at minute 20, P1 free again
O-0002 rider P1
O-0003 rider null
waiting: [O-0003]
P3 comes online at minute 20
O-0003 rider P3
waiting: []
@@ -0,0 +1,8 @@
A cancelled order does not take a rider when one appears
========================================================
no riders online; waiting: [O-0001, O-0002]
O-0001 cancelled, then P1 comes online
O-0001 rider null, status CANCELLED
O-0002 rider P1
waiting: []
@@ -0,0 +1,9 @@
Cancel and reject give back stock, kitchen slot and rider
=========================================================
start : stock b1=10, kitchen slots used=0, P1=AVAILABLE
placed 3 x b1 : stock b1=7, kitchen slots used=0, P1=AVAILABLE
cancelled while PLACED : stock b1=10, kitchen slots used=0, P1=AVAILABLE
placed 4, accepted : stock b1=6, kitchen slots used=1, P1=BUSY (rider P1)
cancelled while ACCEPTED : stock b1=10, kitchen slots used=0, P1=AVAILABLE
placed 2, rejected : stock b1=10, kitchen slots used=0, P1=AVAILABLE
+7
View File
@@ -0,0 +1,7 @@
16 buyers, 10 portions, 5000 rounds
===================================
Timing dependent: the naive counts differ from run to run; the locked counts never do.
naive (check, then write): rounds that sold more than 10: 21 of 5000, worst round sold 12
locked (check and write together): rounds that oversold: 0, undersold: 0 of 5000
@@ -0,0 +1,8 @@
16 orders reach for one free rider, 5000 rounds
===============================================
Timing dependent: the naive count differs from run to run; the compare-and-set count never does.
naive, check then write, nothing in between: rounds where more than one order got the rider: 0 of 5000, most winners in one round 1
naive, with a yield between the check and the write: rounds where more than one order got the rider: 389 of 5000, most winners in one round 7
atomic (compare-and-set), no gap needed: rounds with anything other than one winner: 0 of 5000
@@ -0,0 +1,6 @@
200 orders accepted from 8 threads, 20 riders
=============================================
orders with a rider: 20
distinct riders used : 20
still waiting : 180
@@ -0,0 +1,7 @@
Burger Lab cooks 2 at a time: 50 orders, 16 threads tapping accept
==================================================================
rounds: 300
accepted per round: 2 (every round)
refused per round : 48 (every round)
totals: accepted 600, refused 14400
@@ -0,0 +1,7 @@
The restaurant rejects while the customer cancels, 2000 rounds
==============================================================
The thread released first tends to win, so the two roles swap threads every round to exercise both orders.
Who wins depends on timing; that exactly one wins, and that stock comes back once, never does.
rounds: 2000, reject won 1000, cancel won 1000
+6
View File
@@ -0,0 +1,6 @@
Double tap and client retries: one key, one order
=================================================
same key twice: O-0001 and O-0001, stock left 8
new key : O-0002, stock left 6
16 threads, one key: distinct orders 1, stock left 5
+25
View File
@@ -0,0 +1,25 @@
12 restaurants, 20x20 km grid, 240 minutes of orders, seed 42
=============================================================
Every strategy faces the identical orders. Columns: average and 90th percentile minutes from placing to door,
average km a rider rides empty to the restaurant, average minutes ready food waits for a rider, average minutes
a rider waits at the restaurant for the food, longest the waiting queue got, deliveries per rider (fewest-most).
Comfortable: 40 riders, 200 orders
strategy avg min p90 min empty km food wait rider wt max queue per rider
nearest 26.4 34 4.1 0.4 6.3 0 2-8
rated<=5km 26.4 34 4.3 0.4 5.9 0 0-8
longest-idle 35.8 54 10.9 9.8 2.2 0 4-7
Tight: 30 riders, 200 orders
strategy avg min p90 min empty km food wait rider wt max queue per rider
nearest 30.4 43 7.3 4.5 3.9 1 4-8
rated<=5km 29.6 40 6.8 3.6 4.0 0 4-9
longest-idle 42.0 59 12.5 16.1 1.4 13 5-8
Saturated: 30 riders, 300 orders
strategy avg min p90 min empty km food wait rider wt max queue per rider
nearest 93.1 147 12.6 67.4 0.5 90 8-12
rated<=5km 98.5 156 13.0 72.8 0.4 99 7-12
longest-idle 93.1 147 12.6 67.4 0.5 90 8-12
+64
View File
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm.interviewlab</groupId>
<artifactId>food-delivery</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>java-interview-lab :: food-delivery</name>
<description>
Runnable companion code for ankurm.com's "Low-Level Design: Food Delivery App in Java" article: order state machine, partner assignment
strategies, a dispatcher with a pending queue, atomic stock and kitchen capacity, and a seeded tick simulation.
</description>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>6.1.3</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<argLine>-Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Regenerates every file in output/. Needs JDK 25 and Maven. The first Maven run must be online.
# Every file is written by a JUnit test that asserts the same numbers it prints, so the figures
# in the article are assertions: they fail the build the moment they stop being true.
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p output
mvn -B -q -T1 test
echo "done:"; ls -1 output
@@ -0,0 +1,7 @@
package com.ankurm.interviewlab.fooddelivery;
public record Bill(long subtotalPaise, long deliveryFeePaise, long taxPaise) {
public long totalPaise() {
return subtotalPaise + deliveryFeePaise + taxPaise;
}
}
@@ -0,0 +1,3 @@
package com.ankurm.interviewlab.fooddelivery;
public record Customer(String id, String name, Point location) {}
@@ -0,0 +1,59 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/** A rider. The claim on a rider is one compare-and-set, so two orders can never both get the same rider. */
public final class DeliveryPartner {
private final String id;
private final String name;
private final double rating;
private final AtomicReference<PartnerStatus> status = new AtomicReference<>(PartnerStatus.AVAILABLE);
private final AtomicInteger deliveries = new AtomicInteger();
private volatile Point location;
private volatile long idleSince;
public DeliveryPartner(String id, String name, double rating, Point location) {
this.id = id;
this.name = name;
this.rating = rating;
this.location = location;
}
public String id() { return id; }
public String name() { return name; }
public double rating() { return rating; }
public Point location() { return location; }
public long idleSince() { return idleSince; }
public int deliveries() { return deliveries.get(); }
public PartnerStatus status() { return status.get(); }
public boolean isAvailable() { return status.get() == PartnerStatus.AVAILABLE; }
/** Atomically AVAILABLE to BUSY. Exactly one caller out of any number of racing callers gets true. */
public boolean tryClaim() {
return status.compareAndSet(PartnerStatus.AVAILABLE, PartnerStatus.BUSY);
}
/** Puts a claimed partner back without touching location or idle time (an assignment that did not stick). */
void unclaim() {
status.compareAndSet(PartnerStatus.BUSY, PartnerStatus.AVAILABLE);
}
/** A finished (or cancelled) job: the partner is where the job ended and idle from now. */
void release(Point where, long now) {
this.location = where;
this.idleSince = now;
status.compareAndSet(PartnerStatus.BUSY, PartnerStatus.AVAILABLE);
}
void recordDelivery() { deliveries.incrementAndGet(); }
public boolean goOffline() {
return status.compareAndSet(PartnerStatus.AVAILABLE, PartnerStatus.OFFLINE);
}
public boolean goOnline(long now) {
idleSince = now;
return status.compareAndSet(PartnerStatus.OFFLINE, PartnerStatus.AVAILABLE);
}
}
@@ -0,0 +1,81 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BiConsumer;
/**
* Matches accepted orders to free partners. Orders that find nobody wait in a first-in-first-out queue and are
* matched the moment a partner frees up. A single drain lock keeps the queue consistent; the partner itself is
* still claimed with a compare-and-set, so a partner going offline at the same moment cannot be double-booked.
*/
public final class Dispatcher {
private final List<DeliveryPartner> partners = new CopyOnWriteArrayList<>();
private final Queue<Order> pending = new ConcurrentLinkedQueue<>();
private final Object drainLock = new Object();
private final PartnerAssignmentStrategy strategy;
private final BiConsumer<Order, DeliveryPartner> onAssigned;
Dispatcher(PartnerAssignmentStrategy strategy, BiConsumer<Order, DeliveryPartner> onAssigned) {
this.strategy = strategy;
this.onAssigned = onAssigned;
}
void register(DeliveryPartner partner) {
partners.add(partner);
}
public int pendingCount() { return pending.size(); }
public List<String> pendingIds() { return pending.stream().map(Order::id).toList(); }
void dispatch(Order order) {
pending.add(order);
drain();
}
void partnerFreed(DeliveryPartner partner, Point where, long now) {
partner.release(where, now);
drain();
}
void partnerOnline(DeliveryPartner partner, long now) {
partner.goOnline(now);
drain();
}
private void drain() {
synchronized (drainLock) {
while (true) {
Order head = pending.peek();
if (head == null) return;
if (!head.needsPartner()) { // cancelled or already served while it waited
pending.poll();
continue;
}
DeliveryPartner claimed = claimFor(head);
if (claimed == null) return; // nobody free: the head waits, and so does everyone behind it
pending.poll();
if (head.tryAssign(claimed.id())) {
onAssigned.accept(head, claimed);
} else {
claimed.unclaim(); // the order was cancelled between the check and the assignment
}
}
}
}
private DeliveryPartner claimFor(Order order) {
List<DeliveryPartner> candidates = new ArrayList<>(partners.stream().filter(DeliveryPartner::isAvailable).toList());
while (!candidates.isEmpty()) {
DeliveryPartner pick = strategy.pick(order.pickup(), candidates).orElse(null);
if (pick == null) return null;
if (pick.tryClaim()) return pick;
candidates.remove(pick); // somebody else got there first; choose again from the rest
}
return null;
}
}
@@ -0,0 +1,36 @@
package com.ankurm.interviewlab.fooddelivery;
/** Every business-rule failure is one of these, so a caller can catch the family or a single case. */
public abstract sealed class FoodDeliveryException extends RuntimeException {
protected FoodDeliveryException(String message) {
super(message);
}
public static final class NotFound extends FoodDeliveryException {
public NotFound(String what) { super(what + " not found"); }
}
public static final class InvalidOrder extends FoodDeliveryException {
public InvalidOrder(String why) { super(why); }
}
public static final class OutOfStock extends FoodDeliveryException {
public OutOfStock(String why) { super(why); }
}
public static final class KitchenBusy extends FoodDeliveryException {
public KitchenBusy(String restaurant, int capacity) {
super(restaurant + " is at kitchen capacity (" + capacity + " active orders)");
}
}
public static final class IllegalTransition extends FoodDeliveryException {
public IllegalTransition(String orderId, OrderStatus from, OrderStatus to) {
super(orderId + " cannot move from " + from + " to " + to + "; allowed from " + from + ": " + from.allowedNext());
}
}
public static final class NoPartnerAssigned extends FoodDeliveryException {
public NoPartnerAssigned(String orderId) { super(orderId + " has no delivery partner yet, so it cannot be picked up"); }
}
}
@@ -0,0 +1,203 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
/** The facade a controller would call. It owns the rules; {@link Order} owns the status. */
public final class FoodDeliveryService {
public static final int MAX_QUANTITY_PER_ITEM = 20;
public static final int MAX_DELIVERY_KM = 15;
private final Map<String, Restaurant> restaurants = new ConcurrentHashMap<>();
private final Map<String, Customer> customers = new ConcurrentHashMap<>();
private final Map<String, DeliveryPartner> partners = new ConcurrentHashMap<>();
private final Map<String, Order> orders = new ConcurrentHashMap<>();
private final Map<String, Order> byIdempotencyKey = new ConcurrentHashMap<>();
private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();
private final AtomicLong sequence = new AtomicLong();
private final TickClock clock;
private final PricingPolicy pricing;
private final StockLedger stock;
private final Dispatcher dispatcher;
public FoodDeliveryService(TickClock clock, PricingPolicy pricing, StockLedger stock, PartnerAssignmentStrategy strategy) {
this.clock = clock;
this.pricing = pricing;
this.stock = stock;
this.dispatcher = new Dispatcher(strategy, (order, partner) ->
listeners.forEach(l -> l.partnerAssigned(order.id(), partner.id(), clock.now())));
}
// ---- registration ------------------------------------------------------------------------------------------
public void addRestaurant(Restaurant r) { restaurants.put(r.id(), r); }
public void addCustomer(Customer c) { customers.put(c.id(), c); }
public void addPartner(DeliveryPartner p) {
partners.put(p.id(), p);
dispatcher.register(p);
}
public void addListener(OrderListener l) { listeners.add(l); }
public Dispatcher dispatcher() { return dispatcher; }
public StockLedger stock() { return stock; }
public Restaurant restaurant(String id) { return find(restaurants, id, "restaurant"); }
public DeliveryPartner partner(String id) { return find(partners, id, "partner"); }
public Order order(String id) { return find(orders, id, "order"); }
// ---- search ------------------------------------------------------------------------------------------------
/** Open restaurants within {@code radiusKm} of {@code from} that serve a dish containing {@code dish} (blank matches all). */
public List<RestaurantResult> search(Point from, String dish, int radiusKm, RestaurantRanking ranking) {
String needle = dish == null ? "" : dish.toLowerCase();
List<RestaurantResult> results = new ArrayList<>();
for (Restaurant r : restaurants.values()) {
int km = from.km(r.location());
if (!r.isOpen() || km > radiusKm) continue;
List<String> matches = r.menu().values().stream()
.map(MenuItem::name).filter(n -> n.toLowerCase().contains(needle)).sorted().toList();
if (!matches.isEmpty()) results.add(new RestaurantResult(r, km, matches));
}
results.sort(ranking);
return results;
}
// ---- placing -----------------------------------------------------------------------------------------------
/**
* Places an order. The same idempotency key always returns the same order, so a double tap or a client
* retry after a timeout cannot create (or charge for) a second one.
*/
public Order placeOrder(String idempotencyKey, String customerId, String restaurantId, Map<String, Integer> items) {
if (idempotencyKey == null || idempotencyKey.isBlank()) {
throw new FoodDeliveryException.InvalidOrder("an idempotency key is required");
}
return byIdempotencyKey.computeIfAbsent(idempotencyKey, k -> create(customerId, restaurantId, items));
}
private Order create(String customerId, String restaurantId, Map<String, Integer> items) {
Customer customer = find(customers, customerId, "customer");
Restaurant restaurant = find(restaurants, restaurantId, "restaurant");
if (!restaurant.isOpen()) throw new FoodDeliveryException.InvalidOrder(restaurant.name() + " is closed");
if (items == null || items.isEmpty()) throw new FoodDeliveryException.InvalidOrder("the cart is empty");
int km = customer.location().km(restaurant.location());
if (km > MAX_DELIVERY_KM) {
throw new FoodDeliveryException.InvalidOrder(restaurant.name() + " is " + km + " km away; we deliver up to " + MAX_DELIVERY_KM + " km");
}
List<OrderLine> lines = new ArrayList<>();
long subtotal = 0;
for (var e : items.entrySet()) {
MenuItem item = restaurant.item(e.getKey());
if (item == null) throw new FoodDeliveryException.InvalidOrder(restaurant.name() + " has no item " + e.getKey());
int qty = e.getValue();
if (qty < 1 || qty > MAX_QUANTITY_PER_ITEM) {
throw new FoodDeliveryException.InvalidOrder("quantity for " + item.name() + " must be 1 to " + MAX_QUANTITY_PER_ITEM + ", got " + qty);
}
OrderLine line = new OrderLine(item.id(), item.name(), qty, item.pricePaise());
lines.add(line);
subtotal += line.totalPaise();
}
stock.reserve(restaurantId, items);
String id = String.format("O-%04d", sequence.incrementAndGet());
Order order = new Order(id, customerId, restaurantId, lines, pricing.price(subtotal, km),
restaurant.location(), customer.location(), clock.now());
orders.put(id, order);
publish(order.history().get(0));
return order;
}
// ---- restaurant side ---------------------------------------------------------------------------------------
/** Takes a kitchen slot, accepts the order and asks the dispatcher for a partner. */
public Order accept(String orderId) {
Order order = order(orderId);
Restaurant restaurant = restaurant(order.restaurantId());
if (!restaurant.tryReserveKitchenSlot()) {
throw new FoodDeliveryException.KitchenBusy(restaurant.name(), restaurant.capacity());
}
OrderEvent event;
try {
event = order.moveTo(OrderStatus.ACCEPTED, clock.now());
} catch (RuntimeException e) {
restaurant.releaseKitchenSlot(); // the slot was taken for an order that could not be accepted
throw e;
}
publish(event);
dispatcher.dispatch(order);
return order;
}
public Order reject(String orderId) {
Order order = order(orderId);
publish(order.moveTo(OrderStatus.REJECTED, clock.now()));
stock.release(order.restaurantId(), order.quantities());
return order;
}
public Order startPreparing(String orderId) {
Order order = order(orderId);
publish(order.moveTo(OrderStatus.PREPARING, clock.now()));
return order;
}
public Order markReady(String orderId) {
Order order = order(orderId);
publish(order.moveTo(OrderStatus.READY, clock.now()));
restaurant(order.restaurantId()).releaseKitchenSlot();
return order;
}
// ---- customer and partner side -----------------------------------------------------------------------------
/** Allowed until the kitchen starts cooking (PLACED or ACCEPTED); gives back stock, the kitchen slot and the partner. */
public Order cancel(String orderId) {
Order order = order(orderId);
OrderEvent event = order.moveTo(OrderStatus.CANCELLED, clock.now());
publish(event);
stock.release(order.restaurantId(), order.quantities());
if (event.from() == OrderStatus.ACCEPTED) {
restaurant(order.restaurantId()).releaseKitchenSlot();
if (event.partnerId() != null) {
DeliveryPartner partner = partner(event.partnerId());
dispatcher.partnerFreed(partner, partner.location(), clock.now());
}
}
return order;
}
public Order pickUp(String orderId) {
Order order = order(orderId);
publish(order.moveTo(OrderStatus.PICKED_UP, clock.now()));
return order;
}
public Order deliver(String orderId) {
Order order = order(orderId);
OrderEvent event = order.moveTo(OrderStatus.DELIVERED, clock.now());
publish(event);
DeliveryPartner partner = partner(event.partnerId());
partner.recordDelivery();
dispatcher.partnerFreed(partner, order.dropoff(), clock.now());
return order;
}
public void partnerOffline(String partnerId) { partner(partnerId).goOffline(); }
public void partnerOnline(String partnerId) { dispatcher.partnerOnline(partner(partnerId), clock.now()); }
// ---- helpers -----------------------------------------------------------------------------------------------
private void publish(OrderEvent event) {
listeners.forEach(l -> l.statusChanged(event));
}
private static <T> T find(Map<String, T> map, String id, String what) {
T found = map.get(id);
if (found == null) throw new FoodDeliveryException.NotFound(what + " " + id);
return found;
}
}
@@ -0,0 +1,60 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Stock held per restaurant. The check and the decrement happen inside one lock on that restaurant's stock,
* so the check can never be stale by the time it is acted on; different restaurants never wait for each other.
*/
public final class Inventory implements StockLedger {
private final Map<String, Map<String, Integer>> byRestaurant = new ConcurrentHashMap<>();
@Override
public void setStock(String restaurantId, String itemId, int quantity) {
Map<String, Integer> stock = stockOf(restaurantId);
synchronized (stock) {
stock.put(itemId, quantity);
}
}
@Override
public void reserve(String restaurantId, Map<String, Integer> quantities) {
Map<String, Integer> stock = stockOf(restaurantId);
synchronized (stock) {
for (var e : quantities.entrySet()) {
Integer have = stock.get(e.getKey());
if (have != null && have < e.getValue()) {
throw new FoodDeliveryException.OutOfStock(
e.getKey() + ": wanted " + e.getValue() + ", only " + have + " left");
}
}
for (var e : quantities.entrySet()) {
stock.computeIfPresent(e.getKey(), (k, have) -> have - e.getValue());
}
}
}
@Override
public void release(String restaurantId, Map<String, Integer> quantities) {
Map<String, Integer> stock = stockOf(restaurantId);
synchronized (stock) {
for (var e : quantities.entrySet()) {
stock.computeIfPresent(e.getKey(), (k, have) -> have + e.getValue());
}
}
}
@Override
public int available(String restaurantId, String itemId) {
Map<String, Integer> stock = stockOf(restaurantId);
synchronized (stock) {
return stock.getOrDefault(itemId, Integer.MAX_VALUE);
}
}
private Map<String, Integer> stockOf(String restaurantId) {
return byRestaurant.computeIfAbsent(restaurantId, r -> new HashMap<>());
}
}
@@ -0,0 +1,19 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
/** The partner who has waited longest without a job: a fairness rule, not an efficiency rule. */
public final class LongestIdle implements PartnerAssignmentStrategy {
@Override
public Optional<DeliveryPartner> pick(Point restaurant, List<DeliveryPartner> available) {
return available.stream().min(Comparator
.comparingLong(DeliveryPartner::idleSince)
.thenComparingInt((DeliveryPartner p) -> p.location().km(restaurant))
.thenComparing(DeliveryPartner::id));
}
@Override
public String name() { return "longest-idle"; }
}
@@ -0,0 +1,7 @@
package com.ankurm.interviewlab.fooddelivery;
public record MenuItem(String id, String name, long pricePaise) {
public MenuItem {
if (pricePaise <= 0) throw new IllegalArgumentException("price must be positive: " + id);
}
}
@@ -0,0 +1,12 @@
package com.ankurm.interviewlab.fooddelivery;
/** Money is a whole number of paise everywhere; this class only turns it into text. */
public final class Money {
private Money() {}
public static String rs(long paise) {
String sign = paise < 0 ? "-" : "";
long abs = Math.abs(paise);
return String.format("%sRs %d.%02d", sign, abs / 100, abs % 100);
}
}
@@ -0,0 +1,17 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
/** The closest free partner to the restaurant; ties go to the lower id so a run is repeatable. */
public final class NearestPartner implements PartnerAssignmentStrategy {
@Override
public Optional<DeliveryPartner> pick(Point restaurant, List<DeliveryPartner> available) {
return available.stream().min(
Comparator.comparingInt((DeliveryPartner p) -> p.location().km(restaurant)).thenComparing(DeliveryPartner::id));
}
@Override
public String name() { return "nearest"; }
}
@@ -0,0 +1,82 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* An order and the only place its status changes. Every mutator is synchronized on the order, so two
* threads racing to move the same order (restaurant rejects while the customer cancels) are serialized
* and exactly one of them finds the status it expected.
*/
public final class Order {
private final String id;
private final String customerId;
private final String restaurantId;
private final List<OrderLine> lines;
private final Bill bill;
private final Point pickup;
private final Point dropoff;
private final List<OrderEvent> history = new ArrayList<>();
private OrderStatus status = OrderStatus.PLACED;
private String partnerId;
Order(String id, String customerId, String restaurantId, List<OrderLine> lines, Bill bill, Point pickup, Point dropoff, long now) {
this.id = id;
this.customerId = customerId;
this.restaurantId = restaurantId;
this.lines = List.copyOf(lines);
this.bill = bill;
this.pickup = pickup;
this.dropoff = dropoff;
history.add(new OrderEvent(id, null, OrderStatus.PLACED, now, null));
}
public String id() { return id; }
public String customerId() { return customerId; }
public String restaurantId() { return restaurantId; }
public List<OrderLine> lines() { return lines; }
public Bill bill() { return bill; }
public Point pickup() { return pickup; }
public Point dropoff() { return dropoff; }
/** Item id to quantity, in the order the customer added them. */
public Map<String, Integer> quantities() {
Map<String, Integer> q = new LinkedHashMap<>();
for (OrderLine l : lines) q.merge(l.itemId(), l.quantity(), Integer::sum);
return q;
}
public synchronized OrderStatus status() { return status; }
public synchronized String partnerId() { return partnerId; }
public synchronized List<OrderEvent> history() { return List.copyOf(history); }
/** Moves to {@code next} if the table allows it from the current status; otherwise throws and changes nothing. */
synchronized OrderEvent moveTo(OrderStatus next, long now) {
if (!status.canMoveTo(next)) {
throw new FoodDeliveryException.IllegalTransition(id, status, next);
}
if (next == OrderStatus.PICKED_UP && partnerId == null) {
throw new FoodDeliveryException.NoPartnerAssigned(id);
}
OrderEvent event = new OrderEvent(id, status, next, now, partnerId);
status = next;
history.add(event);
return event;
}
/** A partner can only be attached while the food is still on its way to being handed over. */
private static final Set<OrderStatus> NEEDS_PARTNER = Set.of(OrderStatus.ACCEPTED, OrderStatus.PREPARING, OrderStatus.READY);
synchronized boolean needsPartner() {
return partnerId == null && NEEDS_PARTNER.contains(status);
}
synchronized boolean tryAssign(String partner) {
if (!needsPartner()) return false;
partnerId = partner;
return true;
}
}
@@ -0,0 +1,4 @@
package com.ankurm.interviewlab.fooddelivery;
/** One step in an order's history. {@code from} is null for the first event. */
public record OrderEvent(String orderId, OrderStatus from, OrderStatus to, long at, String partnerId) {}
@@ -0,0 +1,8 @@
package com.ankurm.interviewlab.fooddelivery;
/** A line copies the name and price at order time, so a later menu change cannot rewrite a past order. */
public record OrderLine(String itemId, String name, int quantity, long unitPricePaise) {
public long totalPaise() {
return unitPricePaise * quantity;
}
}
@@ -0,0 +1,8 @@
package com.ankurm.interviewlab.fooddelivery;
/** Observer: notifications, analytics and the customer's live tracking screen all hang off this. */
public interface OrderListener {
void statusChanged(OrderEvent event);
default void partnerAssigned(String orderId, String partnerId, long at) {}
}
@@ -0,0 +1,31 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.EnumSet;
import java.util.Set;
/**
* The whole order lifecycle as one table. There are eight legal moves out of sixty-four possible pairs;
* everything else is rejected by {@link Order#moveTo}.
*/
public enum OrderStatus {
PLACED, ACCEPTED, PREPARING, READY, PICKED_UP, DELIVERED, REJECTED, CANCELLED;
public Set<OrderStatus> allowedNext() {
return switch (this) {
case PLACED -> EnumSet.of(ACCEPTED, REJECTED, CANCELLED);
case ACCEPTED -> EnumSet.of(PREPARING, CANCELLED);
case PREPARING -> EnumSet.of(READY);
case READY -> EnumSet.of(PICKED_UP);
case PICKED_UP -> EnumSet.of(DELIVERED);
case DELIVERED, REJECTED, CANCELLED -> EnumSet.noneOf(OrderStatus.class);
};
}
public boolean canMoveTo(OrderStatus next) {
return allowedNext().contains(next);
}
public boolean isTerminal() {
return allowedNext().isEmpty();
}
}
@@ -0,0 +1,11 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.List;
import java.util.Optional;
/** Picks one partner from a list of free ones. It does not claim anyone; the dispatcher does that atomically. */
public interface PartnerAssignmentStrategy {
Optional<DeliveryPartner> pick(Point restaurant, List<DeliveryPartner> available);
String name();
}
@@ -0,0 +1,3 @@
package com.ankurm.interviewlab.fooddelivery;
public enum PartnerStatus { AVAILABLE, BUSY, OFFLINE }
@@ -0,0 +1,13 @@
package com.ankurm.interviewlab.fooddelivery;
/** A spot on a city grid. One unit is one kilometre; distance is Manhattan, because roads are a grid, not a straight line. */
public record Point(int x, int y) {
public int km(Point other) {
return Math.abs(x - other.x) + Math.abs(y - other.y);
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
}
@@ -0,0 +1,6 @@
package com.ankurm.interviewlab.fooddelivery;
/** Turns a food subtotal and a distance into a bill. Pricing changes often, so it sits behind an interface. */
public interface PricingPolicy {
Bill price(long subtotalPaise, int distanceKm);
}
@@ -0,0 +1,28 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
/** The best-rated partner within {@code radiusKm} of the restaurant; if nobody is that close, falls back to the nearest. */
public final class RatedWithinRadius implements PartnerAssignmentStrategy {
private final int radiusKm;
private final NearestPartner fallback = new NearestPartner();
public RatedWithinRadius(int radiusKm) {
this.radiusKm = radiusKm;
}
@Override
public Optional<DeliveryPartner> pick(Point restaurant, List<DeliveryPartner> available) {
List<DeliveryPartner> near = available.stream().filter(p -> p.location().km(restaurant) <= radiusKm).toList();
if (near.isEmpty()) return fallback.pick(restaurant, available);
return near.stream().min(Comparator
.comparingDouble(DeliveryPartner::rating).reversed()
.thenComparingInt((DeliveryPartner p) -> p.location().km(restaurant))
.thenComparing(DeliveryPartner::id));
}
@Override
public String name() { return "rated<=" + radiusKm + "km"; }
}
@@ -0,0 +1,54 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/** A kitchen with a menu and a limit on how many orders it can cook at once. */
public final class Restaurant {
private final String id;
private final String name;
private final Point location;
private final double rating;
private final int capacity;
private final Map<String, MenuItem> menu = new LinkedHashMap<>();
private final AtomicInteger activeOrders = new AtomicInteger();
private volatile boolean open = true;
public Restaurant(String id, String name, Point location, double rating, int capacity, List<MenuItem> items) {
this.id = id;
this.name = name;
this.location = location;
this.rating = rating;
this.capacity = capacity;
items.forEach(i -> menu.put(i.id(), i));
}
public String id() { return id; }
public String name() { return name; }
public Point location() { return location; }
public double rating() { return rating; }
public int capacity() { return capacity; }
public Map<String, MenuItem> menu() { return Map.copyOf(menu); }
public MenuItem item(String itemId) { return menu.get(itemId); }
public int activeOrders() { return activeOrders.get(); }
public boolean isOpen() { return open; }
public void setOpen(boolean open) { this.open = open; }
/**
* Takes one of the kitchen's slots, or says no. A compare-and-set loop, so fifty staff tapping
* "accept" at once can never push the count past the capacity.
*/
boolean tryReserveKitchenSlot() {
while (true) {
int current = activeOrders.get();
if (current >= capacity) return false;
if (activeOrders.compareAndSet(current, current + 1)) return true;
}
}
void releaseKitchenSlot() {
activeOrders.decrementAndGet();
}
}
@@ -0,0 +1,22 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.Comparator;
/** How search results are ordered. Both rules end in the id so equal results never swap places between runs. */
public enum RestaurantRanking implements Comparator<RestaurantResult> {
NEAREST {
@Override
public int compare(RestaurantResult a, RestaurantResult b) {
return Comparator.comparingInt(RestaurantResult::km)
.thenComparing(r -> r.restaurant().id()).compare(a, b);
}
},
TOP_RATED {
@Override
public int compare(RestaurantResult a, RestaurantResult b) {
return Comparator.comparingDouble((RestaurantResult r) -> r.restaurant().rating()).reversed()
.thenComparingInt(RestaurantResult::km)
.thenComparing(r -> r.restaurant().id()).compare(a, b);
}
}
}
@@ -0,0 +1,5 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.List;
public record RestaurantResult(Restaurant restaurant, int km, List<String> matchingDishes) {}
@@ -0,0 +1,144 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* A minute-by-minute city. Demand (who orders from where, and when) comes from a seeded generator, so every
* strategy faces exactly the same orders and the only thing that differs between runs is who delivers them.
* Riders travel 2 minutes per km (30 km/h on a Manhattan grid).
*/
public final class Simulation {
public static final int MINUTES_PER_KM = 2;
public static final int GRID = 20;
public record Demand(int arriveAt, String restaurantId, Point customer, int prepMinutes) {}
public record Result(String strategy, int delivered, double avgMinutes, int p90Minutes, double avgEmptyKm,
double avgFoodWaitMinutes, double avgRiderWaitMinutes, int maxQueue,
int minPerRider, int maxPerRider, int finishedAt) {}
private static final class Run {
final Order order;
final int readyAt;
boolean ready, picked, done;
long partnerArrive = -1, deliverAt = -1, pickedUpAt, placedAt, deliveredAt;
int emptyKm;
Run(Order order, int readyAt, long placedAt) {
this.order = order;
this.readyAt = readyAt;
this.placedAt = placedAt;
}
}
private Simulation() {}
public static List<Restaurant> restaurants(long seed, int count) {
Random rnd = new Random(seed);
List<Restaurant> list = new ArrayList<>();
for (int i = 1; i <= count; i++) {
list.add(new Restaurant("R" + i, "Restaurant " + i, new Point(rnd.nextInt(GRID), rnd.nextInt(GRID)),
3.5 + rnd.nextInt(16) / 10.0, 1000, List.of(new MenuItem("meal", "Meal", 25000))));
}
return list;
}
public static List<DeliveryPartner> partners(long seed, int count) {
Random rnd = new Random(seed + 1);
List<DeliveryPartner> list = new ArrayList<>();
for (int i = 1; i <= count; i++) {
list.add(new DeliveryPartner(String.format("P%02d", i), "Rider " + i, 3.5 + rnd.nextInt(16) / 10.0,
new Point(rnd.nextInt(GRID), rnd.nextInt(GRID))));
}
return list;
}
/** Customers live within 6 km (each way) of the restaurant they order from, inside the delivery radius. */
public static List<Demand> demand(long seed, int restaurantCount, int orders, int horizonMinutes) {
Random rnd = new Random(seed + 2);
List<Restaurant> rs = restaurants(seed, restaurantCount);
List<Demand> list = new ArrayList<>();
for (int i = 0; i < orders; i++) {
Restaurant r = rs.get(rnd.nextInt(restaurantCount));
Point home = new Point(clamp(r.location().x() + rnd.nextInt(13) - 6), clamp(r.location().y() + rnd.nextInt(13) - 6));
list.add(new Demand(rnd.nextInt(horizonMinutes), r.id(), home, 8 + rnd.nextInt(13)));
}
list.sort(Comparator.comparingInt(Demand::arriveAt));
return list;
}
private static int clamp(int v) {
return Math.max(0, Math.min(GRID - 1, v));
}
public static Result run(long seed, int restaurantCount, int partnerCount, int orderCount, int horizon,
PartnerAssignmentStrategy strategy) {
TickClock clock = new TickClock();
FoodDeliveryService service = new FoodDeliveryService(clock, new StandardPricing(), new Inventory(), strategy);
restaurants(seed, restaurantCount).forEach(service::addRestaurant);
partners(seed, partnerCount).forEach(service::addPartner);
List<Demand> demand = demand(seed, restaurantCount, orderCount, horizon);
List<Run> active = new ArrayList<>();
List<Run> all = new ArrayList<>();
int next = 0, delivered = 0, maxQueue = 0;
long t = 0;
for (; delivered < orderCount; t++) {
clock.set(t);
for (Run r : active) { // a) hand over what is due
if (r.picked && !r.done && r.deliverAt <= t) {
service.deliver(r.order.id());
r.done = true;
r.deliveredAt = t;
delivered++;
}
}
active.removeIf(r -> r.done);
while (next < demand.size() && demand.get(next).arriveAt() <= t) { // b) new orders
Demand d = demand.get(next);
String cid = "C" + next;
service.addCustomer(new Customer(cid, "Customer " + next, d.customer()));
Order o = service.placeOrder("sim-" + next, cid, d.restaurantId(), Map.of("meal", 1));
service.accept(o.id());
service.startPreparing(o.id());
Run run = new Run(o, (int) t + d.prepMinutes(), t);
active.add(run);
all.add(run);
next++;
}
for (Run r : active) { // c) kitchens and riders
if (!r.ready && t >= r.readyAt) {
service.markReady(r.order.id());
r.ready = true;
}
String pid = r.order.partnerId();
if (pid != null && r.partnerArrive < 0) {
r.emptyKm = service.partner(pid).location().km(r.order.pickup());
r.partnerArrive = t + (long) r.emptyKm * MINUTES_PER_KM;
}
if (r.ready && !r.picked && r.partnerArrive >= 0 && t >= r.partnerArrive) {
service.pickUp(r.order.id());
r.picked = true;
r.pickedUpAt = t;
r.deliverAt = t + (long) r.order.pickup().km(r.order.dropoff()) * MINUTES_PER_KM;
}
}
maxQueue = Math.max(maxQueue, service.dispatcher().pendingCount());
}
List<Integer> totals = all.stream().map(r -> (int) (r.deliveredAt - r.placedAt)).sorted().toList();
int p90 = totals.get((int) Math.ceil(totals.size() * 0.9) - 1);
List<DeliveryPartner> ps = partners(seed, partnerCount).stream().map(p -> service.partner(p.id())).toList();
return new Result(strategy.name(), delivered,
totals.stream().mapToInt(Integer::intValue).average().orElse(0), p90,
all.stream().mapToInt(r -> r.emptyKm).average().orElse(0),
all.stream().mapToLong(r -> r.pickedUpAt - r.readyAt).average().orElse(0),
all.stream().mapToLong(r -> Math.max(0, r.readyAt - r.partnerArrive)).average().orElse(0),
maxQueue,
ps.stream().mapToInt(DeliveryPartner::deliveries).min().orElse(0),
ps.stream().mapToInt(DeliveryPartner::deliveries).max().orElse(0), (int) t - 1);
}
}
@@ -0,0 +1,15 @@
package com.ankurm.interviewlab.fooddelivery;
/** Rs 20 plus Rs 8 per km delivery, free from Rs 599 of food; 5% tax on food only, rounded half up to the paise. */
public final class StandardPricing implements PricingPolicy {
public static final long BASE_FEE = 2000;
public static final long PER_KM = 800;
public static final long FREE_DELIVERY_FROM = 59900;
@Override
public Bill price(long subtotalPaise, int distanceKm) {
long fee = subtotalPaise >= FREE_DELIVERY_FROM ? 0 : BASE_FEE + PER_KM * distanceKm;
long tax = (subtotalPaise * 5 + 50) / 100;
return new Bill(subtotalPaise, fee, tax);
}
}
@@ -0,0 +1,15 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.Map;
/** Limited stock per restaurant item ("only 10 portions left"). Items with no entry are unlimited. */
public interface StockLedger {
void setStock(String restaurantId, String itemId, int quantity);
/** All lines or none: if any line is short, nothing is taken and {@link FoodDeliveryException.OutOfStock} is thrown. */
void reserve(String restaurantId, Map<String, Integer> quantities);
void release(String restaurantId, Map<String, Integer> quantities);
int available(String restaurantId, String itemId);
}
@@ -0,0 +1,12 @@
package com.ankurm.interviewlab.fooddelivery;
import java.util.concurrent.atomic.AtomicLong;
/** A logical clock in minutes. Tests and the simulation set it by hand, which keeps every timestamp repeatable. */
public final class TickClock {
private final AtomicLong now = new AtomicLong();
public long now() { return now.get(); }
public void set(long minute) { now.set(minute); }
public void advance(long minutes) { now.addAndGet(minutes); }
}
@@ -0,0 +1,92 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Fixtures;
import com.ankurm.interviewlab.fooddelivery.support.Race;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AcceptRaceTest {
@Test
void kitchenCapacityHoldsUnderConcurrentAccepts() throws Exception {
Transcript out = Transcript.start("11-accept-capacity.txt", "Burger Lab cooks 2 at a time: 50 orders, 16 threads tapping accept");
ExecutorService pool = Race.pool(16);
int rounds = 300, accepted = 0, refused = 0;
try {
for (int r = 0; r < rounds; r++) {
FoodDeliveryService svc = Fixtures.city(new TickClock(), new NearestPartner());
List<Order> orders = new ArrayList<>();
for (int i = 0; i < 50; i++) orders.add(svc.placeOrder("k" + i, "C1", "R4", Map.of("g1", 1)));
AtomicInteger next = new AtomicInteger(), ok = new AtomicInteger(), busy = new AtomicInteger();
Race.run(pool, 16, () -> {
int i;
while ((i = next.getAndIncrement()) < orders.size()) {
try {
svc.accept(orders.get(i).id());
ok.incrementAndGet();
} catch (FoodDeliveryException.KitchenBusy e) {
busy.incrementAndGet();
}
}
return null;
});
assertEquals(2, ok.get());
assertEquals(48, busy.get());
assertEquals(2, svc.restaurant("R4").activeOrders());
long inStatus = orders.stream().filter(o -> o.status() == OrderStatus.ACCEPTED).count();
assertEquals(2, inStatus, "refused orders stay PLACED");
accepted += ok.get();
refused += busy.get();
}
} finally {
pool.shutdown();
}
out.line("rounds: " + rounds).line("accepted per round: 2 (every round)").line("refused per round : 48 (every round)")
.line("totals: accepted " + accepted + ", refused " + refused);
out.flush();
}
@Test
void rejectAndCancelRaceExactlyOneWins() throws Exception {
Transcript out = Transcript.start("11b-reject-vs-cancel.txt", "The restaurant rejects while the customer cancels, 2000 rounds");
out.line("The thread released first tends to win, so the two roles swap threads every round to exercise both orders.")
.line("Who wins depends on timing; that exactly one wins, and that stock comes back once, never does.").blank();
ExecutorService pool = Race.pool(2);
int rounds = 2000, rejectWon = 0, cancelWon = 0;
try {
for (int r = 0; r < rounds; r++) {
final int round = r;
FoodDeliveryService svc = Fixtures.city(new TickClock(), new NearestPartner());
svc.stock().setStock("R1", "b1", 10);
Order o = svc.placeOrder("k", "C1", "R1", Map.of("b1", 3));
AtomicInteger side = new AtomicInteger();
List<Boolean> results = Race.run(pool, 2, () -> {
boolean isReject = (side.getAndIncrement() == 0) == (round % 2 == 0);
try {
if (isReject) svc.reject(o.id()); else svc.cancel(o.id());
return true;
} catch (FoodDeliveryException.IllegalTransition e) {
return false;
}
});
assertEquals(1, results.stream().filter(b -> b).count(), "exactly one of the two succeeds");
assertEquals(10, svc.stock().available("R1", "b1"), "stock is given back once, not twice");
if (o.status() == OrderStatus.REJECTED) rejectWon++; else cancelWon++;
assertEquals(2, o.history().size());
}
} finally {
pool.shutdown();
}
out.line("rounds: " + rounds + ", reject won " + rejectWon + ", cancel won " + cancelWon);
assertEquals(rounds, rejectWon + cancelWon);
out.flush();
}
}
@@ -0,0 +1,53 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Fixtures;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AssignmentTest {
private static String pick(PartnerAssignmentStrategy strategy) {
FoodDeliveryService svc = Fixtures.city(new TickClock(), strategy);
Order o = svc.placeOrder("k", "C1", "R1", Map.of("b1", 1));
svc.accept(o.id());
return o.partnerId();
}
@Test
void threeStrategiesThreeDifferentRiders() {
Transcript out = Transcript.start("06-assignment.txt", "Same order, same three free riders, three strategies");
out.line("Order pickup: Biryani House (2,3)")
.line(" P1 Imran at (3,3) 1 km away rating 4.2 idle since minute 30")
.line(" P2 Kavya at (6,2) 5 km away rating 4.8 idle since minute 20")
.line(" P3 Sunil at (2,6) 3 km away rating 4.5 idle since minute 10")
.blank();
String nearest = pick(new NearestPartner());
String rated5 = pick(new RatedWithinRadius(5));
String rated2 = pick(new RatedWithinRadius(2));
String idle = pick(new LongestIdle());
out.line(String.format("%-14s -> %s", "nearest", nearest))
.line(String.format("%-14s -> %s (all three are within 5 km, so the best rating wins)", "rated<=5km", rated5))
.line(String.format("%-14s -> %s (only P1 is within 2 km)", "rated<=2km", rated2))
.line(String.format("%-14s -> %s (P3 has waited longest)", "longest-idle", idle));
assertEquals("P1", nearest);
assertEquals("P2", rated5);
assertEquals("P1", rated2);
assertEquals("P3", idle);
out.flush();
}
@Test
void radiusFallsBackToNearestWhenNobodyIsClose() {
FoodDeliveryService svc = Fixtures.city(new TickClock(), new RatedWithinRadius(0));
Order o = svc.placeOrder("k", "C1", "R1", Map.of("b1", 1));
svc.accept(o.id());
Transcript out = Transcript.start("06b-radius-fallback.txt", "rated<=0km: nobody is that close, so it falls back to the nearest");
out.line("assigned: " + o.partnerId());
assertEquals("P1", o.partnerId());
out.flush();
}
}
@@ -0,0 +1,54 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Fixtures;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CancelRejectTest {
private static String snapshot(FoodDeliveryService svc, String partnerId) {
return "stock b1=" + svc.stock().available("R1", "b1")
+ ", kitchen slots used=" + svc.restaurant("R1").activeOrders()
+ ", " + partnerId + "=" + svc.partner(partnerId).status();
}
@Test
void everythingAnOrderHeldComesBack() {
TickClock clock = new TickClock();
FoodDeliveryService svc = Fixtures.city(clock, new NearestPartner());
svc.stock().setStock("R1", "b1", 10);
Transcript out = Transcript.start("08-cancel-reject.txt", "Cancel and reject give back stock, kitchen slot and rider");
out.line("start : " + snapshot(svc, "P1"));
Order a = svc.placeOrder("a", "C1", "R1", Map.of("b1", 3));
out.line("placed 3 x b1 : " + snapshot(svc, "P1"));
assertEquals(7, svc.stock().available("R1", "b1"));
svc.cancel(a.id());
out.line("cancelled while PLACED : " + snapshot(svc, "P1"));
assertEquals(10, svc.stock().available("R1", "b1"));
Order b = svc.placeOrder("b", "C1", "R1", Map.of("b1", 4));
svc.accept(b.id());
out.line("placed 4, accepted : " + snapshot(svc, "P1") + " (rider " + b.partnerId() + ")");
assertEquals(1, svc.restaurant("R1").activeOrders());
assertEquals(PartnerStatus.BUSY, svc.partner("P1").status());
svc.cancel(b.id());
out.line("cancelled while ACCEPTED : " + snapshot(svc, "P1"));
assertEquals(10, svc.stock().available("R1", "b1"));
assertEquals(0, svc.restaurant("R1").activeOrders());
assertEquals(PartnerStatus.AVAILABLE, svc.partner("P1").status());
Order c = svc.placeOrder("c", "C1", "R1", Map.of("b1", 2));
svc.reject(c.id());
out.line("placed 2, rejected : " + snapshot(svc, "P1"));
assertEquals(10, svc.stock().available("R1", "b1"));
assertEquals(OrderStatus.REJECTED, c.status());
out.flush();
}
}
@@ -0,0 +1,79 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Fixtures;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class DispatchQueueTest {
@Test
void ordersWaitInFirstInFirstOutOrderForARider() {
TickClock clock = new TickClock();
FoodDeliveryService svc = Fixtures.city(clock, new NearestPartner());
svc.partnerOffline("P2");
svc.partnerOffline("P3"); // only Imran is left
Transcript out = Transcript.start("07-dispatch-queue.txt", "One rider, three orders: the queue and what frees it");
Order a = svc.placeOrder("a", "C1", "R1", Map.of("b1", 1));
Order b = svc.placeOrder("b", "C1", "R4", Map.of("g1", 1));
Order c = svc.placeOrder("c", "C2", "R2", Map.of("d1", 1));
for (Order o : List.of(a, b, c)) svc.accept(o.id());
out.line("three orders accepted, one rider (P1) online");
out.line(" " + a.id() + " rider " + a.partnerId());
out.line(" " + b.id() + " rider " + b.partnerId());
out.line(" " + c.id() + " rider " + c.partnerId());
out.line(" waiting: " + svc.dispatcher().pendingIds());
assertEquals("P1", a.partnerId());
assertNull(b.partnerId());
assertEquals(List.of("O-0002", "O-0003"), svc.dispatcher().pendingIds());
for (Order o : List.of(a)) { svc.startPreparing(o.id()); svc.markReady(o.id()); svc.pickUp(o.id()); }
clock.set(20);
svc.deliver(a.id());
out.blank().line("O-0001 delivered at minute 20, P1 free again");
out.line(" " + b.id() + " rider " + b.partnerId());
out.line(" " + c.id() + " rider " + c.partnerId());
out.line(" waiting: " + svc.dispatcher().pendingIds());
assertEquals("P1", b.partnerId(), "the older waiting order gets the rider first");
assertNull(c.partnerId());
assertEquals(List.of("O-0003"), svc.dispatcher().pendingIds());
svc.partnerOnline("P3");
out.blank().line("P3 comes online at minute 20");
out.line(" " + c.id() + " rider " + c.partnerId());
out.line(" waiting: " + svc.dispatcher().pendingIds());
assertEquals("P3", c.partnerId());
assertEquals(0, svc.dispatcher().pendingCount());
out.flush();
}
@Test
void anOrderCancelledWhileWaitingIsSkipped() {
TickClock clock = new TickClock();
FoodDeliveryService svc = Fixtures.city(clock, new NearestPartner());
for (String id : new String[]{"P1", "P2", "P3"}) svc.partnerOffline(id);
Transcript out = Transcript.start("07b-cancel-while-waiting.txt", "A cancelled order does not take a rider when one appears");
Order a = svc.placeOrder("a", "C1", "R1", Map.of("b1", 1));
Order b = svc.placeOrder("b", "C1", "R4", Map.of("g1", 1));
svc.accept(a.id());
svc.accept(b.id());
out.line("no riders online; waiting: " + svc.dispatcher().pendingIds());
svc.cancel(a.id());
svc.partnerOnline("P1");
out.line("O-0001 cancelled, then P1 comes online");
out.line(" O-0001 rider " + a.partnerId() + ", status " + a.status());
out.line(" O-0002 rider " + b.partnerId());
out.line(" waiting: " + svc.dispatcher().pendingIds());
assertNull(a.partnerId());
assertEquals("P1", b.partnerId());
assertEquals(0, svc.dispatcher().pendingCount());
out.flush();
}
}
@@ -0,0 +1,49 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Fixtures;
import com.ankurm.interviewlab.fooddelivery.support.Race;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
class IdempotencyTest {
@Test
void aRetriedRequestIsNotASecondOrder() throws Exception {
FoodDeliveryService svc = Fixtures.city(new TickClock(), new NearestPartner());
svc.stock().setStock("R1", "b1", 10);
Transcript out = Transcript.start("12-idempotency.txt", "Double tap and client retries: one key, one order");
Order first = svc.placeOrder("tap-1", "C1", "R1", Map.of("b1", 2));
Order again = svc.placeOrder("tap-1", "C1", "R1", Map.of("b1", 2));
out.line("same key twice: " + first.id() + " and " + again.id() + ", stock left " + svc.stock().available("R1", "b1"));
assertSame(first, again);
assertEquals(8, svc.stock().available("R1", "b1"));
Order other = svc.placeOrder("tap-2", "C1", "R1", Map.of("b1", 2));
out.line("new key : " + other.id() + ", stock left " + svc.stock().available("R1", "b1"));
assertNotSame(first, other);
assertEquals(6, svc.stock().available("R1", "b1"));
ExecutorService pool = Race.pool(16);
try {
List<String> ids = Race.run(pool, 16, () -> svc.placeOrder("tap-3", "C1", "R1", Map.of("b1", 1)).id());
Set<String> distinct = new HashSet<>(ids);
out.line("16 threads, one key: distinct orders " + distinct.size() + ", stock left " + svc.stock().available("R1", "b1"));
assertEquals(1, distinct.size());
assertEquals(5, svc.stock().available("R1", "b1"));
} finally {
pool.shutdown();
}
out.flush();
}
}
@@ -0,0 +1,63 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Fixtures;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LifecycleTest {
@Test
void oneOrderFromPlacedToDelivered() {
TickClock clock = new TickClock();
FoodDeliveryService svc = Fixtures.city(clock, new NearestPartner());
List<String> log = new ArrayList<>();
svc.addListener(new OrderListener() {
@Override public void statusChanged(OrderEvent e) {
log.add(String.format("t=%02d %s %s -> %s", e.at(), e.orderId(), e.from() == null ? "-" : e.from(), e.to()));
}
@Override public void partnerAssigned(String orderId, String partnerId, long at) {
log.add(String.format("t=%02d %s partner %s assigned", at, orderId, partnerId));
}
});
Transcript out = Transcript.start("01-happy-path.txt", "One order, from placed to delivered");
Map<String, Integer> cart = new LinkedHashMap<>();
cart.put("b1", 2);
cart.put("b3", 1);
clock.set(0);
Order o = svc.placeOrder("key-1", "C1", "R1", cart);
out.line("Meera (4,4) orders from Biryani House (2,3), 3 km away").line(" " + Fixtures.describe(o.bill()));
// 2 x 24900 + 4900 = 54700; delivery 2000 + 3 km x 800 = 4400; tax 5% of 54700 = 2735
assertEquals(new Bill(54700, 4400, 2735), o.bill());
assertEquals(61835, o.bill().totalPaise());
clock.set(2); svc.accept(o.id());
assertEquals("P1", o.partnerId(), "nearest free rider to (2,3) is Imran at (3,3), 1 km away");
clock.set(3); svc.startPreparing(o.id());
clock.set(14); svc.markReady(o.id());
clock.set(15); svc.pickUp(o.id());
clock.set(21); svc.deliver(o.id());
out.blank().line("Event log");
log.forEach(l -> out.line(" " + l));
assertEquals(OrderStatus.DELIVERED, o.status());
assertEquals(6, o.history().size());
DeliveryPartner imran = svc.partner("P1");
out.blank().line("After delivery: " + imran.name() + " is " + imran.status() + " at " + imran.location()
+ ", idle since minute " + imran.idleSince() + ", deliveries " + imran.deliveries());
assertEquals(new Point(4, 4), imran.location());
assertEquals(PartnerStatus.AVAILABLE, imran.status());
assertEquals(0, svc.restaurant("R1").activeOrders(), "the kitchen slot came back when the food was ready");
assertTrue(log.contains("t=02 O-0001 partner P1 assigned"));
out.flush();
}
}
@@ -0,0 +1,108 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Race;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PartnerClaimTest {
private static final int THREADS = 16;
private static final int ROUNDS = 5000;
/** The tempting claim: look, then set. */
private static final class NaiveRider {
private volatile PartnerStatus status = PartnerStatus.AVAILABLE;
private final boolean workInTheGap;
NaiveRider(boolean workInTheGap) { this.workInTheGap = workInTheGap; }
boolean claim() {
if (status == PartnerStatus.AVAILABLE) {
if (workInTheGap) Thread.yield(); // stands in for the real work between "is he free?" and "he is ours": a DB read, a log call
status = PartnerStatus.BUSY;
return true;
}
return false;
}
}
@Test
void sixteenOrdersGrabTheSameRider() throws Exception {
Transcript out = Transcript.start("10-partner-claim.txt", "16 orders reach for one free rider, " + ROUNDS + " rounds");
out.line("Timing dependent: the naive count differs from run to run; the compare-and-set count never does.").blank();
ExecutorService pool = Race.pool(THREADS);
try {
for (boolean gap : new boolean[]{false, true}) {
int naiveDoubleBooked = 0, naiveMostWinners = 0;
for (int i = 0; i < ROUNDS; i++) {
NaiveRider rider = new NaiveRider(gap);
int winners = (int) Race.run(pool, THREADS, rider::claim).stream().filter(b -> b).count();
if (winners > 1) naiveDoubleBooked++;
naiveMostWinners = Math.max(naiveMostWinners, winners);
}
out.line("naive, " + (gap ? "with a yield between the check and the write" : "check then write, nothing in between")
+ ": rounds where more than one order got the rider: " + naiveDoubleBooked + " of " + ROUNDS
+ ", most winners in one round " + naiveMostWinners);
}
int casDoubleBooked = 0;
for (int i = 0; i < ROUNDS; i++) {
DeliveryPartner rider = new DeliveryPartner("P", "Rider", 4.0, new Point(0, 0));
int winners = (int) Race.run(pool, THREADS, rider::tryClaim).stream().filter(b -> b).count();
assertEquals(1, winners, "exactly one claim wins");
if (winners != 1) casDoubleBooked++;
}
out.line("atomic (compare-and-set), no gap needed: rounds with anything other than one winner: " + casDoubleBooked + " of " + ROUNDS);
} finally {
pool.shutdown();
}
out.flush();
}
@Test
void twoHundredOrdersTwentyRidersFromEightThreads() throws Exception {
TickClock clock = new TickClock();
FoodDeliveryService svc = new FoodDeliveryService(clock, new StandardPricing(), new Inventory(), new NearestPartner());
svc.addRestaurant(new Restaurant("RX", "Big Kitchen", new Point(5, 5), 4.0, 1000, List.of(new MenuItem("m", "Meal", 10000))));
svc.addCustomer(new Customer("C", "Customer", new Point(6, 6)));
for (int i = 1; i <= 20; i++) svc.addPartner(new DeliveryPartner("P" + i, "Rider " + i, 4.0, new Point(i % 10, i / 2)));
List<Order> orders = new java.util.ArrayList<>();
for (int i = 0; i < 200; i++) orders.add(svc.placeOrder("k" + i, "C", "RX", Map.of("m", 1)));
ExecutorService pool = Race.pool(8);
try {
java.util.concurrent.atomic.AtomicInteger next = new java.util.concurrent.atomic.AtomicInteger();
Race.run(pool, 8, () -> {
int i;
while ((i = next.getAndIncrement()) < orders.size()) svc.accept(orders.get(i).id());
return null;
});
} finally {
pool.shutdown();
}
Set<String> riders = new HashSet<>();
int assigned = 0;
for (Order o : orders) {
if (o.partnerId() != null) {
assigned++;
riders.add(o.partnerId());
}
}
Transcript out = Transcript.start("10b-dispatch-under-load.txt", "200 orders accepted from 8 threads, 20 riders");
out.line("orders with a rider: " + assigned).line("distinct riders used : " + riders.size())
.line("still waiting : " + svc.dispatcher().pendingCount());
assertEquals(20, assigned);
assertEquals(20, riders.size());
assertEquals(180, svc.dispatcher().pendingCount());
assertTrue(riders.stream().allMatch(id -> svc.partner(id).status() == PartnerStatus.BUSY));
out.flush();
}
}
@@ -0,0 +1,31 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Fixtures;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PricingTest {
@Test
void billsForDifferentBasketsAndDistances() {
PricingPolicy pricing = new StandardPricing();
Transcript out = Transcript.start("03-pricing.txt", "Bills: delivery by distance, free delivery from Rs 599, tax rounded half up");
long[][] cases = {{9900, 6}, {54700, 3}, {59900, 12}, {59899, 12}, {10010, 1}, {10030, 1}};
for (long[] c : cases) {
Bill b = pricing.price(c[0], (int) c[1]);
out.line(String.format("food %-11s %2d km -> %s", Money.rs(c[0]), c[1], Fixtures.describe(b)));
}
// Rs 99.00 at 6 km: fee 20 + 6 x 8 = 68; tax 4.95
assertEquals(new Bill(9900, 6800, 495), pricing.price(9900, 6));
// Rs 599.00 exactly qualifies for free delivery; Rs 598.99 does not
assertEquals(0, pricing.price(59900, 12).deliveryFeePaise());
assertEquals(2000 + 800 * 12, pricing.price(59899, 12).deliveryFeePaise());
// 5% of 10010 paise is 500.5 paise: half rounds up to 501; 5% of 10030 is 501.5, which rounds up to 502
assertEquals(501, pricing.price(10010, 1).taxPaise());
assertEquals(502, pricing.price(10030, 1).taxPaise());
out.flush();
}
}
@@ -0,0 +1,45 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Fixtures;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SearchTest {
@Test
void sameRestaurantsRankedTwoWays() {
FoodDeliveryService svc = Fixtures.city(new TickClock(), new NearestPartner());
Point meera = new Point(4, 4);
Transcript out = Transcript.start("05-search.txt", "Search from Meera at (4,4): nearest first versus top rated first");
List<RestaurantResult> nearest = svc.search(meera, "", 10, RestaurantRanking.NEAREST);
out.line("blank query, 10 km, NEAREST");
nearest.forEach(r -> out.line(String.format(" %-14s %d km rating %.1f", r.restaurant().name(), r.km(), r.restaurant().rating())));
// Biryani House is 3 km; Dosa Corner, Pizza Point and Burger Lab are all 6 km, so the id breaks the tie
assertEquals(List.of("R1", "R2", "R3", "R4"), nearest.stream().map(r -> r.restaurant().id()).toList());
List<RestaurantResult> rated = svc.search(meera, "", 10, RestaurantRanking.TOP_RATED);
out.blank().line("blank query, 10 km, TOP_RATED");
rated.forEach(r -> out.line(String.format(" %-14s %d km rating %.1f", r.restaurant().name(), r.km(), r.restaurant().rating())));
assertEquals(List.of("R2", "R1", "R3", "R4"), rated.stream().map(r -> r.restaurant().id()).toList());
List<RestaurantResult> dish = svc.search(meera, "burger", 10, RestaurantRanking.NEAREST);
out.blank().line("query \"burger\"");
dish.forEach(r -> out.line(" " + r.restaurant().name() + ": " + r.matchingDishes()));
assertEquals(List.of("Chicken Burger", "Veg Burger"), dish.get(0).matchingDishes());
List<RestaurantResult> close = svc.search(meera, "", 4, RestaurantRanking.NEAREST);
out.blank().line("radius 4 km: " + close.stream().map(r -> r.restaurant().name()).toList());
assertEquals(1, close.size());
svc.restaurant("R1").setOpen(false);
List<RestaurantResult> afterClose = svc.search(meera, "", 4, RestaurantRanking.NEAREST);
out.line("radius 4 km after Biryani House closes: " + afterClose.size() + " results");
assertEquals(0, afterClose.size());
out.flush();
}
}
@@ -0,0 +1,57 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SimulationTest {
private static final long SEED = 42;
private static List<Simulation.Result> run(Transcript out, String title, int partners, int orders) {
out.line(title);
out.line(String.format(" %-14s %9s %8s %9s %10s %9s %9s %8s", "strategy", "avg min", "p90 min", "empty km", "food wait", "rider wt", "max queue", "per rider"));
List<PartnerAssignmentStrategy> strategies = List.of(new NearestPartner(), new RatedWithinRadius(5), new LongestIdle());
List<Simulation.Result> results = strategies.stream().map(s -> Simulation.run(SEED, 12, partners, orders, 240, s)).toList();
for (Simulation.Result r : results) {
out.line(String.format(" %-14s %9.1f %8d %9.1f %10.1f %9.1f %9d %5d-%d", r.strategy(), r.avgMinutes(), r.p90Minutes(),
r.avgEmptyKm(), r.avgFoodWaitMinutes(), r.avgRiderWaitMinutes(), r.maxQueue(), r.minPerRider(), r.maxPerRider()));
assertEquals(orders, r.delivered());
}
out.blank();
return results;
}
@Test
void strategiesMatterOnlyWhileThereIsAChoice() {
Transcript out = Transcript.start("13-simulation.txt", "12 restaurants, 20x20 km grid, 240 minutes of orders, seed " + SEED);
out.line("Every strategy faces the identical orders. Columns: average and 90th percentile minutes from placing to door,")
.line("average km a rider rides empty to the restaurant, average minutes ready food waits for a rider, average minutes")
.line("a rider waits at the restaurant for the food, longest the waiting queue got, deliveries per rider (fewest-most).")
.blank();
List<Simulation.Result> comfortable = run(out, "Comfortable: 40 riders, 200 orders", 40, 200);
List<Simulation.Result> tight = run(out, "Tight: 30 riders, 200 orders", 30, 200);
List<Simulation.Result> saturated = run(out, "Saturated: 30 riders, 300 orders", 30, 300);
Simulation.Result nearest = comfortable.get(0), idle = comfortable.get(2);
assertTrue(nearest.avgEmptyKm() < idle.avgEmptyKm(), "nearest rides far less empty when there are spare riders");
assertTrue(nearest.avgMinutes() < idle.avgMinutes());
assertTrue(idle.maxPerRider() - idle.minPerRider() < nearest.maxPerRider() - nearest.minPerRider(),
"longest-idle spreads the work more evenly");
assertTrue(tight.get(0).avgMinutes() < tight.get(2).avgMinutes());
Simulation.Result sn = saturated.get(0), si = saturated.get(2);
// With a standing queue there is only ever one free rider when a job is handed out, so there is nothing to choose between.
assertEquals(sn.avgMinutes(), si.avgMinutes());
assertEquals(sn.p90Minutes(), si.p90Minutes());
assertEquals(sn.avgEmptyKm(), si.avgEmptyKm());
assertEquals(sn.finishedAt(), si.finishedAt());
assertEquals(sn.maxQueue(), si.maxQueue());
out.flush();
}
}
@@ -0,0 +1,83 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Fixtures;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class StateMachineTest {
@Test
void eightLegalMovesOutOfSixtyFour() {
Transcript out = Transcript.start("02-state-machine.txt", "Order state machine: which of the 64 moves are legal");
OrderStatus[] all = OrderStatus.values();
StringBuilder header = new StringBuilder(String.format("%-10s", "from \\ to"));
for (OrderStatus to : all) header.append(String.format("%-4s", to.name().substring(0, 3)));
out.line(header.toString());
int legal = 0;
for (OrderStatus from : all) {
StringBuilder row = new StringBuilder(String.format("%-10s", from));
for (OrderStatus to : all) {
boolean ok = from.canMoveTo(to);
if (ok) legal++;
row.append(String.format("%-4s", ok ? "yes" : "."));
}
out.line(row.toString());
}
out.blank().line("legal moves: " + legal + " of " + all.length * all.length);
assertEquals(8, legal);
for (OrderStatus s : all) {
assertEquals(s.allowedNext().isEmpty(), s.isTerminal());
}
out.flush();
}
@Test
void illegalMovesAreRefusedWithAMessageThatNamesTheWayOut() {
TickClock clock = new TickClock();
FoodDeliveryService svc = Fixtures.city(clock, new NearestPartner());
Transcript out = Transcript.start("02b-illegal-moves.txt", "Illegal moves: the exact message, and the status afterwards");
Order o = svc.placeOrder("k", "C1", "R1", Map.of("b1", 1));
String m1 = assertThrows(FoodDeliveryException.IllegalTransition.class, () -> svc.markReady(o.id())).getMessage();
out.line("PLACED, markReady : " + m1).line("status afterwards : " + o.status());
assertEquals("O-0001 cannot move from PLACED to READY; allowed from PLACED: [ACCEPTED, REJECTED, CANCELLED]", m1);
assertEquals(OrderStatus.PLACED, o.status());
svc.accept(o.id());
svc.startPreparing(o.id());
String m2 = assertThrows(FoodDeliveryException.IllegalTransition.class, () -> svc.cancel(o.id())).getMessage();
out.blank().line("PREPARING, cancel : " + m2);
assertEquals("O-0001 cannot move from PREPARING to CANCELLED; allowed from PREPARING: [READY]", m2);
svc.markReady(o.id());
svc.pickUp(o.id());
svc.deliver(o.id());
String m3 = assertThrows(FoodDeliveryException.IllegalTransition.class, () -> svc.cancel(o.id())).getMessage();
out.blank().line("DELIVERED, cancel : " + m3);
assertEquals("O-0001 cannot move from DELIVERED to CANCELLED; allowed from DELIVERED: []", m3);
assertEquals(OrderStatus.DELIVERED, o.status());
out.flush();
}
@Test
void pickUpNeedsAPartnerEvenWhenTheStatusAllowsIt() {
TickClock clock = new TickClock();
FoodDeliveryService svc = Fixtures.city(clock, new NearestPartner());
for (String id : new String[]{"P1", "P2", "P3"}) svc.partnerOffline(id);
Transcript out = Transcript.start("02c-no-partner.txt", "READY to PICKED_UP is legal on paper, but not without a rider");
Order o = svc.placeOrder("k", "C1", "R1", Map.of("b1", 1));
svc.accept(o.id());
svc.startPreparing(o.id());
svc.markReady(o.id());
String m = assertThrows(FoodDeliveryException.NoPartnerAssigned.class, () -> svc.pickUp(o.id())).getMessage();
out.line("all riders offline, order READY").line("pickUp: " + m).line("status afterwards: " + o.status());
assertEquals(OrderStatus.READY, o.status());
out.flush();
}
}
@@ -0,0 +1,67 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.NaiveInventory;
import com.ankurm.interviewlab.fooddelivery.support.Race;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import static org.junit.jupiter.api.Assertions.assertEquals;
class StockRaceTest {
private static final int THREADS = 16;
private static final int STOCK = 10;
private static final int ROUNDS = 5000;
/** Sixteen buyers want one portion each of an item with ten left. Returns how many got one. */
private static int oneRound(StockLedger ledger, ExecutorService pool) throws Exception {
ledger.setStock("R1", "b1", STOCK);
List<Boolean> results = Race.run(pool, THREADS, () -> {
try {
ledger.reserve("R1", Map.of("b1", 1));
return true;
} catch (FoodDeliveryException.OutOfStock e) {
return false;
}
});
return (int) results.stream().filter(b -> b).count();
}
@Test
void lastTenPortionsNaiveVersusLocked() throws Exception {
Transcript out = Transcript.start("09-stock-race.txt", "16 buyers, 10 portions, " + ROUNDS + " rounds");
out.line("Timing dependent: the naive counts differ from run to run; the locked counts never do.").blank();
ExecutorService pool = Race.pool(THREADS);
try {
int naiveOversold = 0, naiveWorst = 0;
StockLedger naive = new NaiveInventory();
for (int i = 0; i < ROUNDS; i++) {
int sold = oneRound(naive, pool);
if (sold > STOCK) naiveOversold++;
naiveWorst = Math.max(naiveWorst, sold);
}
out.line("naive (check, then write): rounds that sold more than " + STOCK + ": " + naiveOversold + " of " + ROUNDS
+ ", worst round sold " + naiveWorst);
int lockedOversold = 0, lockedUndersold = 0;
StockLedger locked = new Inventory();
for (int i = 0; i < ROUNDS; i++) {
int sold = oneRound(locked, pool);
if (sold > STOCK) lockedOversold++;
if (sold < STOCK) lockedUndersold++;
assertEquals(STOCK, sold, "exactly the stock is sold, never more and never less");
assertEquals(0, locked.available("R1", "b1"));
}
out.line("locked (check and write together): rounds that oversold: " + lockedOversold + ", undersold: " + lockedUndersold
+ " of " + ROUNDS);
assertEquals(0, lockedOversold);
assertEquals(0, lockedUndersold);
} finally {
pool.shutdown();
}
out.flush();
}
}
@@ -0,0 +1,55 @@
package com.ankurm.interviewlab.fooddelivery;
import com.ankurm.interviewlab.fooddelivery.support.Fixtures;
import com.ankurm.interviewlab.fooddelivery.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ValidationTest {
@Test
void badRequestsAreRefusedAndLeaveNothingBehind() {
TickClock clock = new TickClock();
FoodDeliveryService svc = Fixtures.city(clock, new NearestPartner());
svc.stock().setStock("R1", "b1", 5);
Transcript out = Transcript.start("04-validation.txt", "Bad requests: the exact message for each, and the stock afterwards");
Map<String, Supplier<Order>> bad = new LinkedHashMap<>();
bad.put("blank key", () -> svc.placeOrder(" ", "C1", "R1", Map.of("b1", 1)));
bad.put("unknown customer", () -> svc.placeOrder("a", "C9", "R1", Map.of("b1", 1)));
bad.put("unknown restaurant", () -> svc.placeOrder("b", "C1", "R9", Map.of("b1", 1)));
bad.put("empty cart", () -> svc.placeOrder("c", "C1", "R1", Map.of()));
bad.put("item from another menu", () -> svc.placeOrder("d", "C1", "R1", Map.of("p1", 1)));
bad.put("quantity zero", () -> svc.placeOrder("e", "C1", "R1", Map.of("b1", 0)));
bad.put("quantity 21", () -> svc.placeOrder("f", "C1", "R1", Map.of("b1", 21)));
bad.put("24 km away", () -> svc.placeOrder("g", "C3", "R3", Map.of("p1", 1)));
bad.put("more than the stock", () -> svc.placeOrder("h", "C1", "R1", Map.of("b1", 6)));
for (var e : bad.entrySet()) {
FoodDeliveryException ex = assertThrows(FoodDeliveryException.class, () -> e.getValue().get());
out.line(String.format("%-24s %s: %s", e.getKey(), ex.getClass().getSimpleName(), ex.getMessage()));
}
assertEquals(5, svc.stock().available("R1", "b1"), "nothing was reserved by any failed request");
svc.restaurant("R2").setOpen(false);
String closed = assertThrows(FoodDeliveryException.InvalidOrder.class,
() -> svc.placeOrder("i", "C1", "R2", Map.of("d1", 1))).getMessage();
out.line(String.format("%-24s %s", "closed restaurant", closed));
assertEquals("Dosa Corner is closed", closed);
// all-or-nothing: the second line is short, so the first line must not be taken either
Map<String, Integer> mixed = new LinkedHashMap<>();
mixed.put("b2", 1);
mixed.put("b1", 9);
svc.stock().setStock("R1", "b2", 3);
assertThrows(FoodDeliveryException.OutOfStock.class, () -> svc.placeOrder("j", "C1", "R1", mixed));
out.blank().line("two-line cart where the second line is short: Veg Biryani stock still " + svc.stock().available("R1", "b2"));
assertEquals(3, svc.stock().available("R1", "b2"));
out.flush();
}
}
@@ -0,0 +1,62 @@
package com.ankurm.interviewlab.fooddelivery.support;
import com.ankurm.interviewlab.fooddelivery.*;
import java.util.List;
/** A small fixed city: four restaurants, three customers, three riders. Coordinates are km on a grid. */
public final class Fixtures {
private Fixtures() {}
public static Restaurant biryaniHouse() {
return new Restaurant("R1", "Biryani House", new Point(2, 3), 4.4, 3, List.of(
new MenuItem("b1", "Chicken Biryani", 24900), new MenuItem("b2", "Veg Biryani", 18900), new MenuItem("b3", "Raita", 4900)));
}
public static Restaurant dosaCorner() {
return new Restaurant("R2", "Dosa Corner", new Point(8, 2), 4.6, 2, List.of(
new MenuItem("d1", "Masala Dosa", 9900), new MenuItem("d2", "Filter Coffee", 4500), new MenuItem("d3", "Idli Vada", 8900)));
}
public static Restaurant pizzaPoint() {
return new Restaurant("R3", "Pizza Point", new Point(5, 9), 4.1, 4, List.of(
new MenuItem("p1", "Margherita Pizza", 19900), new MenuItem("p2", "Paneer Tikka Pizza", 24900), new MenuItem("p3", "Garlic Bread", 12900)));
}
public static Restaurant burgerLab() {
return new Restaurant("R4", "Burger Lab", new Point(1, 1), 3.9, 2, List.of(
new MenuItem("g1", "Veg Burger", 14900), new MenuItem("g2", "Chicken Burger", 17900)));
}
/** Idle since: P3 minute 10, P2 minute 20, P1 minute 30, so "longest idle" is P3. */
public static FoodDeliveryService city(TickClock clock, PartnerAssignmentStrategy strategy) {
return city(clock, strategy, new Inventory());
}
public static FoodDeliveryService city(TickClock clock, PartnerAssignmentStrategy strategy, StockLedger ledger) {
FoodDeliveryService s = new FoodDeliveryService(clock, new StandardPricing(), ledger, strategy);
s.addRestaurant(biryaniHouse());
s.addRestaurant(dosaCorner());
s.addRestaurant(pizzaPoint());
s.addRestaurant(burgerLab());
s.addCustomer(new Customer("C1", "Meera", new Point(4, 4)));
s.addCustomer(new Customer("C2", "Rohan", new Point(9, 9)));
s.addCustomer(new Customer("C3", "Faraway", new Point(19, 19)));
DeliveryPartner p1 = new DeliveryPartner("P1", "Imran", 4.2, new Point(3, 3));
DeliveryPartner p2 = new DeliveryPartner("P2", "Kavya", 4.8, new Point(6, 2));
DeliveryPartner p3 = new DeliveryPartner("P3", "Sunil", 4.5, new Point(2, 6));
for (var e : List.of(java.util.Map.entry(p3, 10L), java.util.Map.entry(p2, 20L), java.util.Map.entry(p1, 30L))) {
e.getKey().goOffline();
e.getKey().goOnline(e.getValue());
}
s.addPartner(p1);
s.addPartner(p2);
s.addPartner(p3);
return s;
}
public static String describe(Bill b) {
return "food " + Money.rs(b.subtotalPaise()) + " + delivery " + Money.rs(b.deliveryFeePaise())
+ " + tax " + Money.rs(b.taxPaise()) + " = " + Money.rs(b.totalPaise());
}
}
@@ -0,0 +1,36 @@
package com.ankurm.interviewlab.fooddelivery.support;
import com.ankurm.interviewlab.fooddelivery.FoodDeliveryException;
import com.ankurm.interviewlab.fooddelivery.StockLedger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* The tempting version: a thread-safe map, and a check followed by a write. Every single call on the map is safe;
* the sequence "read, compare, write" is not, because another thread can act between the read and the write.
* Lives in the tests only: it exists to be shown failing.
*/
public final class NaiveInventory implements StockLedger {
private final Map<String, Integer> stock = new ConcurrentHashMap<>();
@Override public void setStock(String restaurantId, String itemId, int quantity) { stock.put(restaurantId + "/" + itemId, quantity); }
@Override
public void reserve(String restaurantId, Map<String, Integer> quantities) {
for (var e : quantities.entrySet()) {
String key = restaurantId + "/" + e.getKey();
Integer have = stock.get(key);
if (have == null) continue;
if (have < e.getValue()) throw new FoodDeliveryException.OutOfStock(e.getKey() + ": only " + have + " left");
stock.put(key, have - e.getValue());
}
}
@Override
public void release(String restaurantId, Map<String, Integer> quantities) {
quantities.forEach((item, q) -> stock.computeIfPresent(restaurantId + "/" + item, (k, have) -> have + q));
}
@Override public int available(String restaurantId, String itemId) { return stock.getOrDefault(restaurantId + "/" + itemId, Integer.MAX_VALUE); }
}
@@ -0,0 +1,32 @@
package com.ankurm.interviewlab.fooddelivery.support;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/** Releases N tasks at the same instant and collects their results, so a race has the best chance to show. */
public final class Race {
private Race() {}
public static <T> List<T> run(ExecutorService pool, int threads, Callable<T> task) throws Exception {
CyclicBarrier gate = new CyclicBarrier(threads);
List<Future<T>> futures = new ArrayList<>();
for (int i = 0; i < threads; i++) {
futures.add(pool.submit(() -> {
gate.await();
return task.call();
}));
}
List<T> results = new ArrayList<>();
for (Future<T> f : futures) results.add(f.get());
return results;
}
public static ExecutorService pool(int threads) {
return Executors.newFixedThreadPool(threads);
}
}
@@ -0,0 +1,43 @@
package com.ankurm.interviewlab.fooddelivery.support;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Writes output/NN-*.txt while the calling test asserts the same numbers it prints. */
public final class Transcript {
private final Path path;
private final List<String> lines = new ArrayList<>();
private Transcript(Path path, String header) {
this.path = path;
lines.add(header);
lines.add("=".repeat(Math.min(header.length(), 100)));
lines.add("");
}
public static Transcript start(String fileName, String header) {
Path dir = Path.of("output");
try {
Files.createDirectories(dir);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return new Transcript(dir.resolve(fileName), header);
}
public Transcript line(String text) { lines.add(text); return this; }
public Transcript blank() { lines.add(""); return this; }
public void flush() {
try {
Files.write(path, (String.join("\n", lines) + "\n").getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}