AlgoViz

Singleton

medium 60 min

One object and one way to reach it.

Watch lesson4:52

Live changes

New settings while requests run: snapshots, versions, listeners.

The point: one shared object that changes must never show half of a change. Replace the content as a whole.

Failure walk

New host, old password

Three setters, one bad request

  1. 1

    10:00:00.000

    set_host("db2") is called.

  2. 2

    10:00:00.001

    A request reads the host db2 and the password of db1.

  3. 3

    10:00:00.002

    set_password(...) is called. Too late for that request.

Making each setter thread safe does not help. The pair must change at once. Put all values into one read-only object and replace the reference.

Settings that can be replaced

All values that belong together, frozen, with a version.

import threadingfrom dataclasses import dataclass, fieldfrom types import MappingProxyType@dataclass(frozen=True)class Snapshot:    version: int    database_url: str    flags: MappingProxyType = field(default_factory=lambda: MappingProxyType({}))

Lines 6 to 10

Frozen: nobody can change one field. A change is a new snapshot, so a reader can not see half of it.

1 of 3

Why it is built this way

How do readers get the current values?

BreaksPublic fields that are changed one by one
How
Setters on the Singleton.
Limit
Readers see mixtures.
Choose when
Never, once there are two values that belong together.
WorksA read-write lock around everything
How
Readers share, the writer waits.
Limit
A reader that makes two calls can still see two versions.
Choose when
The object is large and changed in place.
StrongReplace an immutable snapshot
How
One reference, read once per request.
Limit
Copies the values on each change.
Choose when
Settings: read all the time, changed rarely.