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

Thread-safe space

One lock per space, and what it does not solve

The point: the change from free to taken must be one step that only one thread can win. Put the check and the act under the same lock.

Bug

What double booking looks like

With several gates, two threads can pass isAvailable() for the same space before either calls park. Reading is not wrong, and writing is not wrong. The pair is. This is check then act, also called time of check to time of use.

Python
free = {"M3"}def gate(name):                    # a generator: each yield lets the other gate run    if "M3" in free:               # check        yield f"{name} sees M3 free"        free.discard("M3")         # act        yield f"{name} prints a ticket for M3"    else:        yield f"{name} shows FULL"north, south = gate("North"), gate("South")for step in (north, south, north, south):   # the unlucky order    print(next(step))
The race without threads. Each yield is a moment where the other gate may run. This order happens rarely in real life, and every time here. Run it.
Edit and run it in your browser

Fix

A space that guards itself

Python
from threading import Lockclass LockedSpot:    def __init__(self, spot_id: str) -> None:        self.id = spot_id        self._lock = Lock()        self._plate: str | None = None    def try_park(self, plate: str) -> bool:        with self._lock:                 # check and act under one lock            if self._plate is not None:                return False             # someone was faster: not an error            self._plate = plate            return True    def leave(self) -> str | None:        with self._lock:            plate, self._plate = self._plate, None            return plate                 # who was here, for the billdef park_anywhere(spots: list[LockedSpot], plate: str) -> LockedSpot | None:    for spot in spots:                   # the loser of a race simply tries the next one        if spot.try_park(plate):            return spot    return Nonespots = [LockedSpot("M1"), LockedSpot("M2")]print(park_anywhere(spots, "A").id, park_anywhere(spots, "B").id, park_anywhere(spots, "C"))
try_park answers yes or no. There is no public is_free, so nobody can build the bug again on top.
Edit and run it in your browser
Java
final class LockedSpot {    private final Object lock = new Object();    private Vehicle vehicle;                       // guarded by lock    boolean tryPark(Vehicle v) {        synchronized (lock) {            if (vehicle != null) return false;            vehicle = v;            return true;        }    }    /** Empties the space and says who was in it, which the bill needs. */    Vehicle removeVehicle() {        synchronized (lock) {            Vehicle removed = vehicle;            vehicle = null;            return removed;        }    }}
The same in Java. The lock object is private and final: synchronized (this) would let outsiders hold our lock.
PartWhyWithout it
Private lock objectOnly this class can lock itSomebody's synchronized (spot) around a slow call stops us
Check inside the lockCheck and act are one stepDouble booking
Return false when takenLosing a race is ordinaryExceptions as traffic signs
leave returns who was thereThe bill needs it, and reading it later is another raceTwo calls with a gap
No lock around final fieldsSize and id never changeWasted time, and a false feeling of safety

Limits

What a lock per space does not do

  1. 1

    It does not find

    You still walk over the spaces and try one after another. With 500 spaces and a nearly full lot that is hundreds of locks for one car.

  2. 2

    It does not count

    Adding up 500 spaces takes 500 locks, and the sum belongs to no single moment.

  3. 3

    It does not cover two spaces

    A bus over five spaces needs five locks, taken in the same order by everybody, or two buses wait for each other for ever.

  4. 4

    It does not protect the plate

    The same car at two gates gets two spaces. Each space is perfectly safe.