Thread-Safe Singleton with Double-Checked Locking and Reset

Quick Overview

Build a lazily created singleton that stays unique when many threads request it at once, with a shared value, an access counter and a reset. It tests double-checked locking, safe publication of a new object, races between reset and lookup, and how memory models differ across languages.

Thread-Safe Singleton with Double-Checked Locking and Reset

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a thread-safe Singleton class that guarantees only one instance is ever created, even when accessed concurrently from multiple threads. The class should expose a `get_instance` accessor that lazily constructs the single instance on first use and returns the same instance on every subsequent call. It should also support storing and retrieving a shared integer value, as well as a counter that tracks how many times `get_instance` has been invoked. Use double-checked locking so that the cost of the creation lock is paid only while the instance is being constructed, and looking up an existing instance stays lock-free. Objects created with `ThreadSafeSingleton()` are lightweight handles. Every handle works on the same shared instance, and that shared instance is the singleton. Implement the following methods: - `get_instance() -> int`: lazily create the instance on first call in a thread-safe manner, increment its access counter, and return its identifier. At most one instance exists at a time, so the identifier is always 1. - `set_value(value: int) -> None`: store the given integer inside the singleton, guarded by the instance lock. - `get_value() -> int`: return the integer currently stored in the singleton, or 0 if no value has been set. - `get_access_count() -> int`: return the number of times `get_instance` has been called since the current instance was created. - `reset() -> None`: destroy the current instance so the next call constructs a fresh one. This clears the stored value and the access count. Example 1: ```text Input: ["ThreadSafeSingleton", "reset", "get_instance", "set_value", "get_value", "get_instance", "get_access_count"] [[], [], [], [42], [], [], []] Output: [null, null, 1, null, 42, 1, 2] Explanation: singleton = ThreadSafeSingleton() # handle singleton.reset() # ensure clean state singleton.get_instance() # -> 1 (creates the one instance, count = 1) singleton.set_value(42) # stored value = 42 singleton.get_value() # -> 42 singleton.get_instance() # -> 1 (same instance, count = 2) singleton.get_access_count() # -> 2 ``` Example 2: ```text Input: ["ThreadSafeSingleton", "reset", "set_value", "set_value", "get_value", "reset", "get_value", "get_access_count"] [[], [], [10], [20], [], [], [], []] Output: [null, null, null, null, 20, null, 0, 0] Explanation: singleton = ThreadSafeSingleton() # handle singleton.reset() # clean state singleton.set_value(10) # stored value = 10 singleton.set_value(20) # stored value = 20 (overwrites) singleton.get_value() # -> 20 singleton.reset() # destroys the instance singleton.get_value() # -> 0 (fresh instance created) singleton.get_access_count() # -> 0 (counter reset) ``` ```hint Two threads, no instance yet Picture two threads that both find no instance on the unlocked read at the same moment. Decide what the thread that acquires the lock second has to do before it builds anything. ``` ```hint Reset in the middle of a lookup Imagine `reset()` runs right after your unlocked check succeeds but before the method hands the instance back. Work out what the caller receives. ``` ### Constraints & Assumptions - The number of operations is between 1 and ${10^4}$. - Values passed to `set_value` are 32-bit signed integers. - Any operation may be called from multiple threads at the same time. ### Clarifying Questions to Ask - Is `reset` only a test hook, or can production code call it while other threads are using the instance? - Which runtime is this for: CPython with the GIL, a free-threaded build, or another language whose memory model I should design for? - Must construction be lazy, or may the instance be created eagerly when the class is defined? ### What a Strong Answer Covers - How the design guarantees a single live instance when several threads find none at the same moment. - What the unlocked fast path may safely read, and what the language's memory model requires so no thread sees a half-built instance. - Which lock guards the stored value and the access counter, and why the counter needs one. - How `reset` interacts with calls that are already running against the old instance. - The cost per operation once the instance exists, compared with taking a lock on every call. ### Follow-up Questions - Why does double-checked locking in Java need the instance field to be `volatile`, and what can go wrong without it? - How do a Python module-level object, Java's holder-class idiom or a C++ function-local static give you a lazy singleton without explicit locking, and why do none of them support `reset`? - What problems do singletons cause in tests, and how would you restructure this code so callers receive the shared state instead of looking it up?

Overview: Build a lazily created singleton that stays unique when many threads request it at once, with a shared value, an access counter and a reset. It tests double-checked locking, safe publication of a new object, races between reset and lookup, and how memory models differ across languages.

Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a thread-safe Singleton class that guarantees only one instance is ever created, even when accessed concurrently from multiple threads.

The class should expose a get_instance accessor that lazily constructs the single instance on first use and returns the same instance on every subsequent call. It should also support storing and retrieving a shared integer value, as well as a counter that tracks how many times get_instance has been invoked.

Use double-checked locking so that the cost of the creation lock is paid only while the instance is being constructed, and looking up an existing instance stays lock-free.

Objects created with ThreadSafeSingleton() are lightweight handles. Every handle works on the same shared instance, and that shared instance is the singleton.

Implement the following methods:

  • get_instance() -> int : lazily create the instance on first call in a thread-safe manner, increment its access counter, and return its identifier. At most one instance exists at a time, so the identifier is always 1.
  • set_value(value: int) -> None : store the given integer inside the singleton, guarded by the instance lock.
  • get_value() -> int : return the integer currently stored in the singleton, or 0 if no value has been set.
  • get_access_count() -> int : return the number of times get_instance has been called since the current instance was created.
  • reset() -> None : destroy the current instance so the next call constructs a fresh one. This clears the stored value and the access count.

Example 1:

Input:
["ThreadSafeSingleton", "reset", "get_instance", "set_value", "get_value", "get_instance", "get_access_count"]
[[],                    [],      [],             [42],        [],          [],             []]

Output: [null, null, 1, null, 42, 1, 2]

Explanation:
singleton = ThreadSafeSingleton()       # handle
singleton.reset()                       # ensure clean state
singleton.get_instance()                # -> 1   (creates the one instance, count = 1)
singleton.set_value(42)                 # stored value = 42
singleton.get_value()                   # -> 42
singleton.get_instance()                # -> 1   (same instance, count = 2)
singleton.get_access_count()            # -> 2

Example 2:

Input:
["ThreadSafeSingleton", "reset", "set_value", "set_value", "get_value", "reset", "get_value", "get_access_count"]
[[],                    [],      [10],        [20],        [],          [],      [],          []]

Output: [null, null, null, null, 20, null, 0, 0]

Explanation:
singleton = ThreadSafeSingleton()       # handle
singleton.reset()                       # clean state
singleton.set_value(10)                 # stored value = 10
singleton.set_value(20)                 # stored value = 20 (overwrites)
singleton.get_value()                   # -> 20
singleton.reset()                       # destroys the instance
singleton.get_value()                   # -> 0   (fresh instance created)
singleton.get_access_count()            # -> 0   (counter reset)

Constraints & Assumptions

  • The number of operations is between 1 and 104{10^4} .
  • Values passed to set_value are 32-bit signed integers.
  • Any operation may be called from multiple threads at the same time.

Clarifying Questions to Ask Guidance

  • Is reset only a test hook, or can production code call it while other threads are using the instance?
  • Which runtime is this for: CPython with the GIL, a free-threaded build, or another language whose memory model I should design for?
  • Must construction be lazy, or may the instance be created eagerly when the class is defined?

What a Strong Answer Covers Guidance

  • How the design guarantees a single live instance when several threads find none at the same moment.
  • What the unlocked fast path may safely read, and what the language's memory model requires so no thread sees a half-built instance.
  • Which lock guards the stored value and the access counter, and why the counter needs one.
  • How reset interacts with calls that are already running against the old instance.
  • The cost per operation once the instance exists, compared with taking a lock on every call.

Follow-up Questions Guidance

  • Why does double-checked locking in Java need the instance field to be volatile , and what can go wrong without it?
  • How do a Python module-level object, Java's holder-class idiom or a C++ function-local static give you a lazy singleton without explicit locking, and why do none of them support reset ?
  • What problems do singletons cause in tests, and how would you restructure this code so callers receive the shared state instead of looking it up?