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

Display board

Observer, order, and slow listeners

The point: when several things must react to one change and the list will grow, let them subscribe. Then take care of order, slowness and failure, which the textbook picture leaves out.

Observer

Who wants to know

Signs listen. The lot does not know them.

0 to nParkingLot- version: int- listeners: List+ subscribe(listener)- changed(size, by)«interface»FreeListener+ onChange(version, free)

1/2One small interface

The lot says: something changed, this is message number 41, these are the free counts. It knows nothing about lamps or phones.

usesimplements

ListenerUsesReacts
Sign at the entranceAll sizesFULL when nothing is left
Sign on each levelIts own levelA number and an arrow
Phone appThe totalA message when 10 or fewer are left, once, not at 9 and 8 again
Light over a spaceOne spaceGreen or red
StatisticsEvery changeWrites to a queue

Bugs

The textbook version has five

TextbookWhat goes wrongRepair
ArrayList of observersSubscribe during a notification: an exception, or a lost observerAn immutable list that is replaced, or CopyOnWriteArrayList
total += delta without a lockTwo gates, one update lost: 3 minus 1 minus 1 is 2 instead of 1Change counts under the lock
Notify inside the lockA slow sign stops all gates. A listener that calls back may never returnCopy under the lock, call after it
Notify outside the lockTwo messages may arrive in the wrong order: FULL, then 1A version number; older messages are dropped
One exception ends the loopA broken sign silences the othersCatch for each listener and log
Repair three causes problem four. Say it before the interviewer does.
Python
from threading import Lockfrom typing import CallableListener = Callable[[int, dict[str, int]], None]      # version, free countsclass Counter:    def __init__(self, counts: dict[str, int]) -> None:        self._lock = Lock()        self._counts = counts        self._version = 0        self._listeners: tuple[Listener, ...] = ()    # replaced, never edited    def subscribe(self, listener: Listener) -> None:        with self._lock:            self._listeners += (listener,)    def change(self, size: str, by: int) -> None:        with self._lock:            self._counts[size] += by            self._version += 1            version, snapshot, listeners = self._version, dict(self._counts), self._listeners        for listener in listeners:                    # outside the lock            try:                listener(version, snapshot)            except Exception as problem:              # one broken sign must not stop the gate                print("sign failed:", problem)class Board:    def __init__(self, name: str) -> None:        self.name, self.shows, self._seen = name, "", 0    def __call__(self, version: int, free: dict[str, int]) -> None:        if version <= self._seen:            return                                    # an older message that came late        self._seen = version        self.shows = "FULL" if not any(free.values()) else " ".join(f"{k} {v}" for k, v in free.items())counter, entrance = Counter({"M": 1}), Board("entrance")counter.subscribe(entrance)counter.subscribe(lambda version, free: 1 / 0)counter.change("M", -1)print(entrance.shows)entrance(0, {"M": 9})print(entrance.shows)
The second listener always fails, and the entrance still shows FULL. The message with version 0 comes late and is ignored.
Edit and run it in your browser

Why the version is needed

How do signs learn about changes?

BreaksThe lot calls each sign
How
entranceBoard.update(); app.push(); inside enter.
Limit
A new sign is a change in the lot, and a slow one stops the gate.
Choose when
Never with more than one.
WorksSigns ask every second
How
free() on a timer.
Limit
Up to a second old, and useless questions at night.
Choose when
A handful of signs. It is simple, it cannot lose a message, and it recovers by itself.
StrongSubscribe, with versions and a queue
How
The lot puts (version, counts) in a queue for each listener, size one, newest wins. A thread for each listener sends.
Limit
More parts. And still a full refresh now and then, in case a message is lost.
Choose when
Many listeners, or changes must show at once.