~learn.
0:00 / 1:19
LLD · Parking lot

Two gates, one free spot, two tickets

transcript

Two cars. Two entry gates. The same instant. Both get a ticket. For the same spot.

Two gates run on two threads. Both call park. Both search for a spot at the same moment. Both see F0-M0 free. Neither has written yet. Both write their car into it. Two tickets. One spot.

The bug lives in a gap. Between I saw it free, and I marked it taken.

Lock only the search? Both still find F0-M0 before either writes. A floor per gate? That just hides the race. Lock find and occupy together. One atomic step. Gate A takes F0-M0. Gate B waits, then gets F0-M1. Pricing touches no shared state. So it runs outside the lock.

Why is one lock enough? ParkingLot is the only class that changes state. Spots, floors and tickets are just data. So there's one place to lock.

The demo proves it. 40 threads race the gates. For just 6 car-sized spots. 6 parked. 6 different spots. Remove the lock, and two share one.

Find and occupy is one step. Never two.

Full breakdown in the lecture.