Singleton
medium 60 minOne 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)Doors and locks
| Door | What happens | Lock |
|---|---|---|
| Reflection in Java | setAccessible(true), then the private constructor runs | Enum: the runtime refuses to create constants by reflection |
| Java serialization | Reading the stream makes a new object | Enum, or readResolve returning the instance |
| Copy | C++ 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 loaders | Each loads the class, each has its static field | Load it from a shared parent loader |
| Two copies of a package | npm installs two versions, each module runs | Deduplicate, or a peer dependency |
| Fork | The child has a copy of the object, with the same open sockets | Build after the fork |
| Subclass | __new__ of the parent returns the parent | Make it final |
| Two processes | Two objects, naturally | A 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; }}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.