Design a parking lot
medium 90 minModel a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.
Watch lesson4:48
Two cars, one space
Locks, compare and set, and databases
The point: there are four tools that make a claim atomic. Choose by where the truth lives: one object, one process, or a database.
Numbers first
Is one lock really too slow?
Before you split a lock, do the sum. Assume one claim under the lock takes 5 microseconds: a few dictionary operations. Assume 10 gates, and a car every 6 seconds at each.
How busy is the lock?
Tools
Four ways to take a space
| Tool | The step that decides | The loser sees | Good for |
|---|---|---|---|
| Mutex | Entering the block | The next free space, after waiting | One process, several facts at once |
| Atomic removal from a concurrent queue | pollFirst() on a ConcurrentLinkedDeque | Another space, or null | One process, one fact |
| Compare and set on the space | compareAndSet(null, plate) | false, tries the next | You already know which space |
| Conditional update in the database | WHERE ticket_id IS NULL, one row changed | Zero rows | Several processes or machines |
final class CasSpot { private final AtomicReference<String> plate = new AtomicReference<>(); boolean tryPark(String newPlate) { // "If it is still null, make it newPlate." One machine step, one winner. return plate.compareAndSet(null, newPlate); } boolean leave(String oldPlate) { return plate.compareAndSet(oldPlate, null); // only the right car frees it }}leave uses it too, so a late message cannot empty a space that another car has taken meanwhile.free = {"M3"}def claim(name): try: free.remove("M3") # one move: it is there and it is mine, or it fails return f"{name} prints a ticket for M3" except KeyError: return f"{name} shows FULL"print(claim("North"))print(claim("South"))remove is the check. In the interleaving above there is no longer a place to pause between the two halves.-- One statement: pick one free space that fits, and take it.UPDATE spotSET ticket_id = :ticketWHERE id = ( SELECT id FROM spot WHERE ticket_id IS NULL AND size >= :smallest ORDER BY size, distance LIMIT 1 FOR UPDATE SKIP LOCKED)RETURNING id; -- no row: nothing was freeSKIP LOCKED lets a second gate pass over a row that another gate is holding, instead of waiting for it. The size column must be stored as a number, so that larger compares as larger.Two styles
Pessimistic and optimistic
Optimistic: try, then look
- Read a version, write with
WHERE version = 7 - Nothing is held while you think
- On conflict read again and retry
- With JPA
@Versionthe conflict comes as an exception, not as a false result - Best when conflicts are rare
Pessimistic: hold, then act
- Lock the row or the object first
- Others wait, nobody retries
- Keep it short, and take several in a fixed order
- A holder that dies must be noticed
- Best when conflicts are common: the last space on a Saturday
More than one
The bus that needs five
Some interviewers want a bus to take five large spaces in a row. Now a claim is five changes, and either all or none may happen. Under one lock this is easy: find the run, check it, take all five, release the lock. Nobody sees four.
If each space has a lock, take them in ascending order and let go of all if one fails. In a database, do it in one transaction. Across two services you would need a compensating step that gives back spaces 1 to 3 when space 4 fails. Inside one process that is a sign that the lock is in the wrong place.
Failure walk
What if it stops halfway?
| It stops after | State | Who repairs it |
|---|---|---|
| Claim, before the ticket is stored (in memory, an exception) | Space gone, nobody has it | try and release; keep this code free of calls that can fail |
| The process dies | Memory is gone, cars are not | Rebuild from the stored tickets: free = all minus active |
| Database: before commit | Nothing happened | Nobody. That is what a transaction is for |
| After commit, before the paper is printed | Car has a space and no paper | Print again from the stored ticket; it is the same ticket |