Loading...
āœ“

12-Hour Money-Back Guarantee

🚚 Delivery Truck Loading System Concurrency Problem

🚚 Delivery Truck Loading System Concurrency Problem

🚚 Delivery Truck Loading System Concurrency Problem

22 Aug 20255 min read

šŸ“ Problem Setup

A logistics company has multiple loading docks where workers load packages into delivery trucks.

  • Each truck has a weight/volume limit.

  • Packages arrive continuously from the warehouse.

  • Multiple workers can attempt to load packages in parallel.

  • Once a truck is full, it should be dispatched immediately, and a new empty truck should arrive at the dock.

āš ļø Concurrency Challenge

Naive approach:
Each worker checks whether the truck has space left and then puts the package in.

Problems

  • Two workers check simultaneously → both see ā€œspace available.ā€

  • Both load packages → truck exceeds capacity.

  • Or, one worker sees ā€œtruck is full,ā€ but another worker just dispatched it → confusion: packages might get lost or assigned incorrectly.

šŸ”‘ Solution Approaches

1. Naive Locking

  • Place a synchronized lock on the truck while loading.

  • Multiple workers try to load packages onto a dock’s current truck.

    • Correctness first: never overfill a truck; never dispatch twice; never lose a package.

      • Only one worker can load at a time.
  • We’ll serialize critical operations with a single lock so only one worker mutates truck state at a time.

šŸ”’ Locking plan (coarse-grained / ā€œmonitorā€)

  • Use one monitor lock per dock (i.e., synchronized on the Dock instance).

    • Why lock the dock (not the truck)?