Loading...
āœ“

12-Hour Money-Back Guarantee

šŸ“¦ Warehouse Packing Simulation Concurrency Problem

šŸ“¦ Warehouse Packing Simulation Concurrency Problem

šŸ“¦ Warehouse Packing Simulation Concurrency Problem

25 Jul 20252 min read

Let's model a warehouse system where multiple workers pack orders concurrently while managing shared resources.

Problem Statement

  • Multiple packing stations process orders simultaneously

  • Shared inventory with limited stock

  • Orders may require multiple items

  • Prevent race conditions during inventory access

  • Handle backorders when stock is insufficient

Solution Approaches

Basic Solution

public class Warehouse {
    private Map<String, Integer> inventory = new HashMap<>();
    
    public boolean pickItem(String sku, int quantity) {
        if (inventory.getOrDefault(sku, 0) >= quantity) {
            inventory.put(sku, inventory.get(sku) - quantity);
            return true;
        }
        return false;
    }
    
    public void restock(String sku, int quantity) {
        inventory.put(sku, inventory.getOrDefault(sku, 0) + quantity);
    }
}

public class PackingStation {
    public void processOrder(Order order, Warehouse warehouse) {
        for (Map.Entry<String, Integer> item : order.getItems().entrySet()) {
            if (!warehouse.pickItem(item.getKey(), item.getValue())) {
                order.backorder();
                return;
            }
        }
        order.pack();
    }
}

Problems

  1. Race Condition: Two threads can oversell stock

  2. Dirty Reads: Temporary negative inventory possible

  3. Lost Updates: Restocks might get overwritten

Fix for Above mentioned problem: Coarse-Grained Synchronization

public class Warehouse {
    private Map<String, Integer> inventory = new HashMap<>();
    
    public synchronized boolean pickItem(String sku, int quantity) {
        if (inventory.getOrDefault(sku, 0) >= quantity) {
            inventory.put(sku, inventory.get(sku) - quantity);
            return true;
        }
        return false;
    }
    
    public synchronized void restock(String sku, int quantity) {
        inventory.put(sku, inventory.getOrDefault(sku, 0) + quantity);
    }
}
  1. Solves race conditions with method-level synchronized

  2. Ensures atomic inventory updates

New Problems

Throughput Bottleneck:

  • Entire warehouse locks during each operation

  • Packing station working with SKU-A blocks SKU-B access

Deadlock Risk:

// Thread 1
synchronized void processOrder() {
    pickItem("A", 1);
    pickItem("B", 1); // Deadlock if Thread 2 holds B and wants A
}