AlgoViz

Design a parking lot

medium 90 min

Model 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?

106 s≈1.7/s1.7×5 μs=8.5 μs/s=0.00085 %\frac{10}{6 \text{ s}} \approx 1.7/\text{s} \qquad 1.7 \times 5\,\mu\text{s} = 8.5\,\mu\text{s/s} = 0.00085\,\%
The assumptions may be wrong by a factor of 1000 and the lock would still be idle 99% of the time. Simple wins, and the reason is a number.

Tools

Four ways to take a space

ToolThe step that decidesThe loser seesGood for
MutexEntering the blockThe next free space, after waitingOne process, several facts at once
Atomic removal from a concurrent queuepollFirst() on a ConcurrentLinkedDequeAnother space, or nullOne process, one fact
Compare and set on the spacecompareAndSet(null, plate)false, tries the nextYou already know which space
Conditional update in the databaseWHERE ticket_id IS NULL, one row changedZero rowsSeveral processes or machines
Java
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    }}
Compare and set: the processor compares and writes in one instruction. leave uses it too, so a late message cannot empty a space that another car has taken meanwhile.
Python
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"))
The same idea with a set: remove is the check. In the interleaving above there is no longer a place to pause between the two halves.
Edit and run it in your browser
SQL
-- 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 free
In PostgreSQL. SKIP 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 @Version the 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 afterStateWho repairs it
Claim, before the ticket is stored (in memory, an exception)Space gone, nobody has ittry and release; keep this code free of calls that can fail
The process diesMemory is gone, cars are notRebuild from the stored tickets: free = all minus active
Database: before commitNothing happenedNobody. That is what a transaction is for
After commit, before the paper is printedCar has a space and no paperPrint again from the stored ticket; it is the same ticket