Loading...
โœ“

12-Hour Money-Back Guarantee

๐Ÿšš Delivery Truck Loading System Concurrency Problem

LLDCoding Article

๐Ÿšš 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)?