AlgoViz

Singleton

medium 60 min

One object and one way to reach it.

Watch lesson4:52

Birth and death

A constructor that fails, a cycle at start, and who closes it.

The point: tutorials end after the object is built. In production the questions are: what if building fails, and who shuts it down?

Birth

When the first build fails

In Java, an exception inside a static initializer leaves the class in an erroneous state. The first caller sees ExceptionInInitializerError, every later one NoClassDefFoundError, until the process is restarted. A database that was down for one second at the wrong time takes the service down for the night.

Python
import threadingclass Pool:    def __init__(self):        if not Pool.database_up:            raise ConnectionError("database is down")    database_up = Falseclass Once:    """Create at most one. A failure is not remembered."""    def __init__(self, create):        self._create, self._lock = create, threading.Lock()        self._value, self._ready = None, False    def get(self):        if self._ready:            return self._value        with self._lock:            if not self._ready:                self._value = self._create()    # may raise: nothing is set                self._ready = True            return self._value    def close(self):        with self._lock:            value, self._value, self._ready = self._value, None, False        return value                            # the caller closes itpool = Once(Pool)try:    pool.get()except ConnectionError as error:    print("first try:", error)Pool.database_up = Trueprint("second try:", pool.get() is pool.get())
A failure is not remembered. The next caller tries again.
Edit and run it in your browser

Who retries?

MechanismAfter a failed build
Java static initializer, holder, enumNever again in this class loader
Java checked lockThe next call tries again, the field is still null
C++ static localThe next call tries again: the variable counts as not initialized
Go sync.OnceCounts as done, even after a panic. The error must be stored
A kept promise in TypeScriptThe rejected promise is kept, unless you clear it
Trying again is not always right. Eight threads that each wait ten seconds for a dead database, one after the other under one lock, are worse than a quick error.

A safe start

Failed is a state with a time, so that callers get a quick error instead of a queue.

Cycles

Two that need each other

Java
final class Log {    static final Log INSTANCE = new Log();    private final String level = Settings.INSTANCE.level();    void info(String s) { if (level.equals("info")) System.out.println(s); }}final class Settings {    static final Settings INSTANCE = new Settings();    private Settings() { Log.INSTANCE.info("loaded"); }   // INSTANCE may still be null    String level() { return "info"; }}
The logger asks the settings for its level. The settings log that they were loaded. Whoever starts first sees null from the other, and two threads that start from both ends can wait for each other for ever.

Hidden dependencies hide cycles. In main the same mistake does not compile: you can not pass an object that you have not built yet. See circular dependencies.

Death

Who closes it?

WayGoodBad
NobodySimple. The system takes the memory and sockets backUnsent data in buffers is lost
Destructor of a C++ staticAutomaticOrder: objects are destroyed in reverse order of construction, and another destructor may still use it
Shutdown hookRuns on a normal endNot when the process is killed, and hooks run side by side in Java
Main owns and closesOrder is visible: stop traffic, drain, close pool, flush logSomebody must write it
Python
def main():    with open_log() as log:        with open_pool(log) as pool:            server = Server(Orders(pool, log))            server.run()            # returns when asked to stop            server.drain(seconds=20)
Main, with the order on the page. The log is opened first and closed last, because the others use it.