AlgoViz

Singleton

medium 60 min

One object and one way to reach it.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:52

See it run

Who asks, who builds, and how many objects exist.

Operations

One for three

Three services of one program ask for the settings. The first question builds them.

Step 1 of 10

Nothing yet

authAuthServiceConfigManagerthe classinstanceNone

Objects: 0

The class is loaded. Its field is empty. No settings object exists.

Step 1: Nothing yet

class ConfigManager:    _instance = None    @classmethod    def get_instance(cls):        if cls._instance is None:            cls._instance = cls._create()        return cls._instanceauth.config = ConfigManager.get_instance()payment.config = ConfigManager.get_instance()analytics.config = ConfigManager.get_instance()
Watch
The instance field
Result
1 object

The constructor runs once, in step four.

In the real world

The same singleton doing real jobs. Pick one and step through it.

Why volatile is needed: another thread sees the address before the content.

Step 1 of 4

A begins

LeeThread Aatget memoryMaxThread BtowerTowerclock0

Creating an object is three steps: get memory, fill it, store the address.

Step 1: A begins

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Check and act without a lock

    critical

    Two threads both see the empty field and both build.

    Wrong
    if cls._instance is None:    cls._instance = cls()
    Right
    with cls._lock:    if cls._instance is None:        cls._instance = cls()
  • No second check

    critical

    The thread that waited builds again, with the lock in its hand.

    Wrong
    if cls._instance is None:    with cls._lock:        cls._instance = cls()
    Right
    if cls._instance is None:    with cls._lock:        if cls._instance is None:            cls._instance = cls()
  • Storing before it is ready

    critical

    Another thread skips the lock and uses an empty object.

    Wrong
    cls._instance = object.__new__(cls)cls._instance.load()
    Right
    fresh = object.__new__(cls)fresh.load()cls._instance = fresh
  • __new__ with __init__

    major

    Python runs __init__ on every call and resets the values.

    Wrong
    def __new__(cls): return the_onedef __init__(self): self.url = DEFAULT
    Right
    the_one = Config()      # at module level# no __new__ needed
  • Per-user data in it

    critical

    There is one object and many users. Asha sees the cart of Lee.

    Wrong
    Cart.get_instance().add(item)
    Right
    cart = carts.of(user)cart.add(item)
  • Fetching it deep inside

    major

    The signature hides what the class needs, and tests cannot replace it.

    Wrong
    def page(self):    flags = Flags.get_instance()
    Right
    def __init__(self, flags):    self._flags = flags

Interview tips

  • Ask first

    • Must there be one?
    • One per what?
    • Who may replace it?
  • Safe by default

    • Java: enum or holder.
    • C++: static local.
    • Python, TS: a module.
  • Keep it boring

    • Read-only if you can.
    • No user data.
    • A close for resources.
  • In an interview

    • Write the short one.
    • Say what breaks it.
    • Offer to pass it in.