All labs ยท beginner ยท about 25 min
๐ The flash sale sold 112 units of an item with 100 in stock
The shop keeps its stock count on a whiteboard. During the sale, shoppers read the count, decided there was enough, and wrote down a smaller number. More games were sold than the shop had. Find out why and fix it.
Java 21JUnit 5๐จ The incident
The shop's stock count lives on a whiteboard. Whenever a shopper wants some, a helper reads the count, checks there is enough, and writes the new smaller number. The board itself is sturdy, so nobody expected trouble. But during the Friday sale, hundreds of shoppers were served at once, and the shop promised 112 games when only 100 existed. Your job: never promise more than the board says, and make sure every promise is taken off the count.
๐ What people saw
- Twelve shoppers were told "yours is on the way" for games the shop never had.
- The count on the board did not match the number of promises made.
- Quiet afternoons were fine. It only went wrong when the doors opened and the queue surged.
[inventory] INFO reserve sku=console-x qty=1 seen=3 left=2 thread=http-nio-12 [inventory] INFO reserve sku=console-x qty=1 seen=3 left=2 thread=http-nio-31 [inventory] INFO reserve sku=console-x qty=1 seen=2 left=1 thread=http-nio-07 [inventory] INFO reserve sku=console-x qty=1 seen=1 left=0 thread=http-nio-19 [inventory] INFO reserve sku=console-x qty=1 seen=1 left=0 thread=http-nio-04 [warehouse] ERROR pick list for console-x asks for 112 units, 100 in bins
โถ๏ธ Start the lab
- Unzip it and open the
flash-sale-oversellfolder in your editor. - Run
mvn test. The failing tests are the bug report: read what they expect. - Fix the code in
src/mainuntilmvn testpasses. Leave the tests alone: they describe what the system must guarantee.
๐ Start reading here
src/main/java/lab/inventory/InventoryService.java
1package lab.inventory;23/** Reserves units of an item for checkout while the stock lasts. */4public class InventoryService {5private final StockStore store;67public InventoryService(StockStore store) {8this.store = store;9}1011/** Returns true if the units were reserved, false if there is not enough stock. */12public boolean reserve(String sku, int quantity) {13int available = store.available(sku);14if (available < quantity) {15return false;16}17store.put(sku, available - quantity);18return true;19}2021public int available(String sku) {22return store.available(sku);23}24}
src/main/java/lab/inventory/StockStore.java
1package lab.inventory;23import java.util.Map;4import java.util.concurrent.ConcurrentHashMap;56/** In-memory stock levels. In production this sits behind a cache or a database. */7public class StockStore {8private final Map<String, Integer> stock = new ConcurrentHashMap<>();910public void put(String sku, int quantity) {11stock.put(sku, quantity);12}1314public int available(String sku) {15return stock.getOrDefault(sku, 0);16}17}
src/test/java/lab/inventory/InventoryServiceTest.java
1package lab.inventory;23import static org.junit.jupiter.api.Assertions.assertEquals;4import static org.junit.jupiter.api.Assertions.assertFalse;5import static org.junit.jupiter.api.Assertions.assertTrue;67import java.util.ArrayList;8import java.util.List;9import java.util.concurrent.CountDownLatch;10import java.util.concurrent.CyclicBarrier;11import java.util.concurrent.ExecutorService;12import java.util.concurrent.Executors;13import java.util.concurrent.Future;14import java.util.concurrent.TimeUnit;15import java.util.concurrent.atomic.AtomicInteger;16import org.junit.jupiter.api.Test;1718class InventoryServiceTest {19static final String SKU = "console-x";2021/** Makes two shoppers read the stock at the same moment, as a busy sale does by chance. */22static class BusyStore extends StockStore {23private final CountDownLatch bothHaveRead = new CountDownLatch(2);2425@Override26public int available(String sku) {27int seen = super.available(sku);28bothHaveRead.countDown();29try {30// Gives up after a while, in case the service never lets a second shopper read.31bothHaveRead.await(1, TimeUnit.SECONDS);32} catch (InterruptedException e) {33Thread.currentThread().interrupt();34}35return seen;36}37}3839/** Lets other threads run between a read and the write that follows it. */40static class JostlingStore extends StockStore {41@Override42public int available(String sku) {43int seen = super.available(sku);44Thread.yield();45return seen;46}47}4849static void reserveInThread(ExecutorService pool, InventoryService svc, int qty, List<Future<Boolean>> out) {50out.add(pool.submit(() -> svc.reserve(SKU, qty)));51}5253@Test54void anOrderForMoreThanIsInStockIsRejected() {55var store = new StockStore();56store.put(SKU, 5);57var service = new InventoryService(store);5859assertFalse(service.reserve(SKU, 6));60assertEquals(5, service.available(SKU));61assertTrue(service.reserve(SKU, 5));62assertEquals(0, service.available(SKU));63assertFalse(service.reserve(SKU, 1));64}6566@Test67void twoShoppersTakingTheLastUnitsAtTheSameMomentCannotBothGetThem() throws Exception {68var store = new BusyStore();69store.put(SKU, 5);70var service = new InventoryService(store);71var pool = Executors.newFixedThreadPool(2);72try {73List<Future<Boolean>> results = new ArrayList<>();74reserveInThread(pool, service, 3, results);75reserveInThread(pool, service, 3, results);7677int sold = 0;78for (Future<Boolean> f : results) if (f.get(10, TimeUnit.SECONDS)) sold += 3;7980assertTrue(sold <= 5, "sold " + sold + " units with only 5 in stock");81assertEquals(5 - sold, service.available(SKU),82"stock left should be 5 minus the " + sold + " units sold");83} finally {84pool.shutdownNow();85}86}8788@Test89void aFlashSaleNeverSellsMoreThanWasInStock() throws Exception {90int stock = 100, shoppers = 16, attemptsEach = 7; // 112 attempts for 100 units91var store = new JostlingStore();92store.put(SKU, stock);93var service = new InventoryService(store);94var sold = new AtomicInteger();95var start = new CyclicBarrier(shoppers);96var pool = Executors.newFixedThreadPool(shoppers);97try {98List<Future<?>> done = new ArrayList<>();99for (int i = 0; i < shoppers; i++) {100done.add(pool.submit(() -> {101start.await(10, TimeUnit.SECONDS);102for (int n = 0; n < attemptsEach; n++) {103if (service.reserve(SKU, 1)) sold.incrementAndGet();104}105return null;106}));107}108for (Future<?> f : done) f.get(30, TimeUnit.SECONDS);109110assertTrue(sold.get() <= stock, "sold " + sold.get() + " units with only " + stock + " in stock");111assertEquals(stock - sold.get(), service.available(SKU),112"every reservation should be reflected in the stock left");113} finally {114pool.shutdownNow();115}116}117}
๐ก Hints
โ What really happened
Fixed it? Or completely stuck? Either way, here's what really happened.