TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

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

Practises๐Ÿ–Š๏ธ Threads, locks and race conditions

๐Ÿšจ 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

โฌ‡ Download the projectNeeds Java 21 and Maven.
  1. Unzip it and open the flash-sale-oversell folder in your editor.
  2. Run mvn test. The failing tests are the bug report: read what they expect.
  3. Fix the code in src/main until mvn test passes. Leave the tests alone: they describe what the system must guarantee.

๐Ÿ“‚ Start reading here

src/main/java/lab/inventory/InventoryService.java
1package lab.inventory;2 3/** Reserves units of an item for checkout while the stock lasts. */4public class InventoryService {5    private final StockStore store;6 7    public InventoryService(StockStore store) {8        this.store = store;9    }10 11    /** Returns true if the units were reserved, false if there is not enough stock. */12    public boolean reserve(String sku, int quantity) {13        int available = store.available(sku);14        if (available < quantity) {15            return false;16        }17        store.put(sku, available - quantity);18        return true;19    }20 21    public int available(String sku) {22        return store.available(sku);23    }24}
src/main/java/lab/inventory/StockStore.java
1package lab.inventory;2 3import java.util.Map;4import java.util.concurrent.ConcurrentHashMap;5 6/** In-memory stock levels. In production this sits behind a cache or a database. */7public class StockStore {8    private final Map<String, Integer> stock = new ConcurrentHashMap<>();9 10    public void put(String sku, int quantity) {11        stock.put(sku, quantity);12    }13 14    public int available(String sku) {15        return stock.getOrDefault(sku, 0);16    }17}
src/test/java/lab/inventory/InventoryServiceTest.java
1package lab.inventory;2 3import static org.junit.jupiter.api.Assertions.assertEquals;4import static org.junit.jupiter.api.Assertions.assertFalse;5import static org.junit.jupiter.api.Assertions.assertTrue;6 7import 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;17 18class InventoryServiceTest {19    static final String SKU = "console-x";20 21    /** Makes two shoppers read the stock at the same moment, as a busy sale does by chance. */22    static class BusyStore extends StockStore {23        private final CountDownLatch bothHaveRead = new CountDownLatch(2);24 25        @Override26        public int available(String sku) {27            int seen = super.available(sku);28            bothHaveRead.countDown();29            try {30                // Gives up after a while, in case the service never lets a second shopper read.31                bothHaveRead.await(1, TimeUnit.SECONDS);32            } catch (InterruptedException e) {33                Thread.currentThread().interrupt();34            }35            return seen;36        }37    }38 39    /** Lets other threads run between a read and the write that follows it. */40    static class JostlingStore extends StockStore {41        @Override42        public int available(String sku) {43            int seen = super.available(sku);44            Thread.yield();45            return seen;46        }47    }48 49    static void reserveInThread(ExecutorService pool, InventoryService svc, int qty, List<Future<Boolean>> out) {50        out.add(pool.submit(() -> svc.reserve(SKU, qty)));51    }52 53    @Test54    void anOrderForMoreThanIsInStockIsRejected() {55        var store = new StockStore();56        store.put(SKU, 5);57        var service = new InventoryService(store);58 59        assertFalse(service.reserve(SKU, 6));60        assertEquals(5, service.available(SKU));61        assertTrue(service.reserve(SKU, 5));62        assertEquals(0, service.available(SKU));63        assertFalse(service.reserve(SKU, 1));64    }65 66    @Test67    void twoShoppersTakingTheLastUnitsAtTheSameMomentCannotBothGetThem() throws Exception {68        var store = new BusyStore();69        store.put(SKU, 5);70        var service = new InventoryService(store);71        var pool = Executors.newFixedThreadPool(2);72        try {73            List<Future<Boolean>> results = new ArrayList<>();74            reserveInThread(pool, service, 3, results);75            reserveInThread(pool, service, 3, results);76 77            int sold = 0;78            for (Future<Boolean> f : results) if (f.get(10, TimeUnit.SECONDS)) sold += 3;79 80            assertTrue(sold <= 5, "sold " + sold + " units with only 5 in stock");81            assertEquals(5 - sold, service.available(SKU),82                "stock left should be 5 minus the " + sold + " units sold");83        } finally {84            pool.shutdownNow();85        }86    }87 88    @Test89    void aFlashSaleNeverSellsMoreThanWasInStock() throws Exception {90        int stock = 100, shoppers = 16, attemptsEach = 7; // 112 attempts for 100 units91        var store = new JostlingStore();92        store.put(SKU, stock);93        var service = new InventoryService(store);94        var sold = new AtomicInteger();95        var start = new CyclicBarrier(shoppers);96        var pool = Executors.newFixedThreadPool(shoppers);97        try {98            List<Future<?>> done = new ArrayList<>();99            for (int i = 0; i < shoppers; i++) {100                done.add(pool.submit(() -> {101                    start.await(10, TimeUnit.SECONDS);102                    for (int n = 0; n < attemptsEach; n++) {103                        if (service.reserve(SKU, 1)) sold.incrementAndGet();104                    }105                    return null;106                }));107            }108            for (Future<?> f : done) f.get(30, TimeUnit.SECONDS);109 110            assertTrue(sold.get() <= stock, "sold " + sold.get() + " units with only " + stock + " in stock");111            assertEquals(stock - sold.get(), service.available(SKU),112                "every reservation should be reflected in the stock left");113        } finally {114            pool.shutdownNow();115        }116    }117}

๐Ÿ’ก Hints

โœ… What really happened

Fixed it? Or completely stuck? Either way, here's what really happened.