AlgoViz

Singleton

medium 60 min

One object and one way to reach it.

Watch lesson4:52

Back doors

Reflection, serialization, copies, loaders, forks: ways to a second object.

The point: a private constructor closes the front door. Know the others, and decide which of them matter to you.

Python

Four surprises in thirty lines

Python
import copyimport pickleclass Config:    _instance = None    def __new__(cls):        if cls._instance is None:            cls._instance = super().__new__(cls)        return cls._instance    def __init__(self):        self.url = "db://main"first = Config()first.url = "db://spare"second = Config()                           # same object, __init__ againprint("after a second call:", first.url)saved = pickle.dumps(first)first.url = "db://third"pickle.loads(saved)                         # no second object, but old valuesprint("after loading a pickle:", first.url)raw = object.__new__(Config)print("object.__new__ makes two:", raw is not first)class Child(Config):    passprint("subclass gets the parent:", type(Child()).__name__)class Sealed:    def __copy__(self): return self    def __deepcopy__(self, memo): return self    def __reduce__(self): return "SEALED"   # pickle by name: the global belowSEALED = Sealed()print("sealed:", copy.copy(SEALED) is SEALED, pickle.loads(pickle.dumps(SEALED)) is SEALED)
The second call resets the url, and loading an old pickle rewinds it. No second object was needed to lose data.
Edit and run it in your browser

Doors and locks

DoorWhat happensLock
Reflection in JavasetAccessible(true), then the private constructor runsEnum: the runtime refuses to create constants by reflection
Java serializationReading the stream makes a new objectEnum, or readResolve returning the instance
CopyC++ copy constructor, clone()Delete or forbid it
Pickle and copy in Python__init__ again, or old state written over the new__reduce__ with the name of the global
Two class loadersEach loads the class, each has its static fieldLoad it from a shared parent loader
Two copies of a packagenpm installs two versions, each module runsDeduplicate, or a peer dependency
ForkThe child has a copy of the object, with the same open socketsBuild after the fork
Subclass__new__ of the parent returns the parentMake it final
Two processesTwo objects, naturallyA lock outside, see the next pages
Java
final class Config implements java.io.Serializable {    private static final long serialVersionUID = 1L;    private static final Config INSTANCE = new Config();    private Config() {        if (INSTANCE != null) throw new IllegalStateException("use getInstance");    }    static Config getInstance() { return INSTANCE; }    private Object readResolve() { return INSTANCE; }}
Without readResolve, writing and reading the object gives a second one.

A worker server forks four children after loading the application. The connection pool is a Singleton. What do you do?

BreaksNothing, each child has its own copy
How
The memory is copied.
Limit
The sockets are not. Four children write to the same connections, and answers get mixed.
Choose when
Never.
WorksCompare the process id in getInstance
How
Remember the id, rebuild if it changed.
Limit
Every caller pays, and the old sockets must be dropped without closing the session of the parent.
Choose when
In a library that can not know when the fork happens.
StrongBuild the pool after the fork
How
Use the start hook of the worker. Nothing is opened before.
Limit
Needs a hook, and discipline about imports that open things.
Choose when
Your own service.