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