
๐ Delivery Truck Loading System Concurrency Problem
๐ 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
synchronizedlock 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.,
synchronizedon theDockinstance).Why lock the dock (not the truck)?