Singleton
medium 60 minOne 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())Who retries?
| Mechanism | After a failed build |
|---|---|
| Java static initializer, holder, enum | Never again in this class loader |
| Java checked lock | The next call tries again, the field is still null |
| C++ static local | The next call tries again: the variable counts as not initialized |
Go sync.Once | Counts as done, even after a panic. The error must be stored |
| A kept promise in TypeScript | The rejected promise is kept, unless you clear it |
A safe start
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"; }}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?
| Way | Good | Bad |
|---|---|---|
| Nobody | Simple. The system takes the memory and sockets back | Unsent data in buffers is lost |
| Destructor of a C++ static | Automatic | Order: objects are destroyed in reverse order of construction, and another destructor may still use it |
| Shutdown hook | Runs on a normal end | Not when the process is killed, and hooks run side by side in Java |
| Main owns and closes | Order is visible: stop traffic, drain, close pool, flush log | Somebody 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)