Programming Search⌘K

Patternadvanced

Multiton

Also called multiton pattern, registry of singletons, keyed singleton, instance per key.

A multiton keeps one instance of a class for each key. A static method returns the instance for a key, creates it on the first request and returns the same object later.

Family
creational-design
Intent
Ensure that a class has one instance for each key, and give a global point of access that returns the instance for a key.
Also called
Registry of Singletons

Intent

Ensure that a class has one instance for each key, and give a global point of access that returns the instance for a key. The multiton generalizes the Singleton pattern: a singleton has one instance for the program, and a multiton has one instance for each key.1

Problem

A program works with money in several currencies. Each currency has a code and a number of decimal places: two for the US dollar, none for the yen. The program compares currencies often, and it wants usd == usd to be a test of identity, not of fields. It also wants to check the code once, when the currency is made, and not at each use.

If each caller creates its own Currency object, the program has many objects for the dollar, and identity means nothing. A single global object does not help, because there are many currencies. The forces are these:

  • The class has many instances, but at most one for each key.
  • The callers ask by key, often from many places and many threads.
  • The set of keys is not known in full when the program starts, or it is too large to create in advance.

Solution

Make the constructor private. Keep a static map from key to instance, and give the class a static method that takes a key. The method looks up the key. If an instance is there, it returns it. If not, it checks the key, creates the instance, stores it and returns it.1

 Caller                    Currency.of(code)                 registry (map)
 ------                    -----------------                 --------------
 of("USD") ------------->  lock; look up "USD" ----------->  absent
                           valid code? create, store ---->  "USD" -> #1
           <-------------  return #1
 of("USD") ------------->  lock; look up "USD" ----------->  "USD" -> #1
           <-------------  return #1 (the same object)
 of("XYZ") ------------->  not a valid code -> error

A multiton differs from a plain map in two ways. Clients cannot add entries, and a request for a key never returns an empty result: the multiton creates the instance on the first request, and returns the same instance for later requests with that key.1

Design Patterns does not describe the multiton as a pattern of its own.1 Its Singleton pattern comes close in two places. A registry of singletons maps names to instances, so that the program can pick a subclass by name. And one of the consequences of Singleton is that it permits a variable number of instances, because the access method controls how many exist.2

Thread safety. Two threads can both find the key absent, and both create an instance. The check and the insert must be one step. A lock around both is the simple form. A concurrent map can do it without a lock in the code, but the details differ by library. Java's ConcurrentHashMap.computeIfAbsent performs the whole call atomically, and calls the function once if the key is absent.3 .NET's ConcurrentDictionary.GetOrAdd adds only one pair for a key, but its factory may be called more than once when threads race,4 so the factory must not have side effects, or the value must be a Lazy<T>.

Example

The example files show one Currency class in each language. of(code) returns the one instance for a code. The program asks for the dollar twice and gets the same object, asks for an unknown code and gets an error, and then eight threads ask for the euro at the same time and get one object:

Language Registry Thread safety
Python a class-level dict and a classmethod threading.Lock
JavaScript a static private Map one thread per agent, so no lock
TypeScript a private static Map, keys as a union type one thread per agent, so no lock
Java a ConcurrentHashMap computeIfAbsent3
C# a ConcurrentDictionary of Lazy<Currency> GetOrAdd4
C++ a static std::map of std::unique_ptr std::mutex
Go a package-level map of pointers sync.Mutex
Rust LazyLock<Mutex<HashMap<_, Arc<_>>>> Mutex
PythonGitHub
import threading


class Currency:
    _DECIMALS = {"USD": 2, "EUR": 2, "JPY": 0}  # the valid keys
    _instances: dict[str, "Currency"] = {}
    _lock = threading.Lock()

    def __init__(self, code: str, decimals: int):
        self.code, self.decimals = code, decimals

    @classmethod
    def of(cls, code: str) -> "Currency":
        with cls._lock:
            instance = cls._instances.get(code)
            if instance is None:
                if code not in cls._DECIMALS:
                    raise ValueError(code)
                instance = cls(code, cls._DECIMALS[code])
                cls._instances[code] = instance  # one instance per key
            return instance

    @classmethod
    def count(cls) -> int:
        return len(cls._instances)


print("USD has", Currency.of("USD").decimals, "decimals")
print("JPY has", Currency.of("JPY").decimals, "decimals")
print("same USD object:", Currency.of("USD") is Currency.of("USD"))
print("instances:", Currency.count())
try:
    Currency.of("XYZ")
except ValueError as e:
    print(f"{e}: unknown currency")

seen, seen_lock = set(), threading.Lock()
start = threading.Barrier(8)


def worker():
    start.wait()  # all eight threads ask at the same time
    c = Currency.of("EUR")
    with seen_lock:
        seen.add(id(c))


threads = [threading.Thread(target=worker) for _ in range(8)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("8 threads ask for EUR:", len(seen), "object")
print("instances:", Currency.count())
Output
USD has 2 decimals
JPY has 0 decimals
same USD object: True
instances: 2
XYZ: unknown currency
8 threads ask for EUR: 1 object
instances: 3
  • Verdict: idiom. A class-level dict and a classmethod give one instance per key. The lock makes the check and the insert one step.
  • logging.getLogger(name) is the standard multiton: calls with the same name always return the same Logger object.
  • A weakref.WeakValueDictionary in place of the dict lets an instance go away when no code uses it, so the registry does not keep every key for ever.
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>

class Currency {
public:
    static const Currency& of(const std::string& code) {
        static const std::map<std::string, int> valid{{"USD", 2}, {"EUR", 2}, {"JPY", 0}};
        auto d = valid.find(code);
        if (d == valid.end()) throw std::invalid_argument(code);
        std::lock_guard<std::mutex> lock(mutex_);
        auto& slot = instances_[code];
        if (!slot) slot.reset(new Currency(code, d->second));  // one instance per key
        return *slot;
    }

    static std::size_t count() {
        std::lock_guard<std::mutex> lock(mutex_);
        return instances_.size();
    }

    Currency(const Currency&) = delete;
    Currency& operator=(const Currency&) = delete;

    const std::string code;
    const int decimals;

private:
    Currency(std::string c, int d) : code(std::move(c)), decimals(d) {}
    static inline std::mutex mutex_;
    static inline std::map<std::string, std::unique_ptr<Currency>> instances_;
};

int main() {
    std::cout << "USD has " << Currency::of("USD").decimals << " decimals\n";
    std::cout << "JPY has " << Currency::of("JPY").decimals << " decimals\n";
    std::cout << "same USD object: " << std::boolalpha
              << (&Currency::of("USD") == &Currency::of("USD")) << "\n";
    std::cout << "instances: " << Currency::count() << "\n";
    try {
        Currency::of("XYZ");
    } catch (const std::invalid_argument& e) {
        std::cout << e.what() << ": unknown currency\n";
    }

    std::mutex seen_mutex;
    std::set<const Currency*> seen;
    std::vector<std::thread> threads;
    for (int i = 0; i < 8; ++i) {
        threads.emplace_back([&] {
            const Currency* c = &Currency::of("EUR");
            std::lock_guard<std::mutex> lock(seen_mutex);
            seen.insert(c);
        });
    }
    for (auto& t : threads) t.join();
    std::cout << "8 threads ask for EUR: " << seen.size() << " object\n";
    std::cout << "instances: " << Currency::count() << "\n";
}
Output
USD has 2 decimals
JPY has 0 decimals
same USD object: true
instances: 2
XYZ: unknown currency
8 threads ask for EUR: 1 object
instances: 3
  • Verdict: idiom. A private constructor, a deleted copy constructor and a static map of std::unique_ptr give one object per key. The map owns the objects, and callers get references.
  • A std::mutex makes the check and the insert one step. A reference into a std::map stays valid when other keys are inserted, so callers can keep it.
JavaGitHub
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

public class Main {
    static final class Currency {
        private static final Map<String, Integer> DECIMALS =
                Map.of("USD", 2, "EUR", 2, "JPY", 0); // the valid keys
        private static final ConcurrentHashMap<String, Currency> INSTANCES =
                new ConcurrentHashMap<>();

        final String code;
        final int decimals;

        private Currency(String code, int decimals) {
            this.code = code;
            this.decimals = decimals;
        }

        static Currency of(String code) {
            Integer d = DECIMALS.get(code);
            if (d == null) throw new IllegalArgumentException(code);
            // one instance per key; the function runs at most once per key
            return INSTANCES.computeIfAbsent(code, c -> new Currency(c, d));
        }

        static int count() {
            return INSTANCES.size();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("USD has " + Currency.of("USD").decimals + " decimals");
        System.out.println("JPY has " + Currency.of("JPY").decimals + " decimals");
        System.out.println("same USD object: " + (Currency.of("USD") == Currency.of("USD")));
        System.out.println("instances: " + Currency.count());
        try {
            Currency.of("XYZ");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage() + ": unknown currency");
        }

        Set<Currency> seen = ConcurrentHashMap.newKeySet();
        CountDownLatch start = new CountDownLatch(1);
        Thread[] threads = new Thread[8];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                try {
                    start.await(); // all eight threads ask at the same time
                } catch (InterruptedException e) {
                    return;
                }
                seen.add(Currency.of("EUR"));
            });
            threads[i].start();
        }
        start.countDown();
        for (Thread t : threads) t.join();
        System.out.println("8 threads ask for EUR: " + seen.size() + " object");
        System.out.println("instances: " + Currency.count());
    }
}
Output
USD has 2 decimals
JPY has 0 decimals
same USD object: true
instances: 2
XYZ: unknown currency
8 threads ask for EUR: 1 object
instances: 3
  • Verdict: stdlib. ConcurrentHashMap.computeIfAbsent performs the whole call atomically, so two threads cannot both create an instance for one key, and the registry needs no lock in the code.
  • java.util.Currency is a multiton in the standard library: there is never more than one Currency instance for a currency, and the class has no public constructor.
  • When the keys are fixed at compile time, an enum is the simpler form. The language creates one instance per constant.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

var usd = Currency.Of("USD");
Console.WriteLine($"USD has {usd.Decimals} decimals");
Console.WriteLine($"JPY has {Currency.Of("JPY").Decimals} decimals");
Console.WriteLine($"same USD object: {ReferenceEquals(Currency.Of("USD"), Currency.Of("USD"))}");
Console.WriteLine($"instances: {Currency.Count}");
try
{
    Currency.Of("XYZ");
}
catch (ArgumentException e)
{
    Console.WriteLine($"{e.Message}: unknown currency");
}

using var start = new Barrier(8);
var tasks = Enumerable.Range(0, 8).Select(i => Task.Factory.StartNew(() =>
{
    start.SignalAndWait(); // all eight threads ask at the same time
    return Currency.Of("EUR");
}, TaskCreationOptions.LongRunning)).ToArray();
var seen = new HashSet<Currency>((await Task.WhenAll(tasks)), ReferenceEqualityComparer.Instance);
Console.WriteLine($"8 threads ask for EUR: {seen.Count} object");
Console.WriteLine($"instances: {Currency.Count}");

sealed class Currency
{
    static readonly Dictionary<string, int> Valid = new() { ["USD"] = 2, ["EUR"] = 2, ["JPY"] = 0 };
    // GetOrAdd can run the factory twice under a race, so the value is a Lazy:
    // only the Lazy that wins the race is ever asked for its value.
    static readonly ConcurrentDictionary<string, Lazy<Currency>> Instances = new();

    public string Code { get; }
    public int Decimals { get; }

    Currency(string code, int decimals) => (Code, Decimals) = (code, decimals);

    public static Currency Of(string code)
    {
        if (!Valid.TryGetValue(code, out var d)) throw new ArgumentException(code);
        return Instances.GetOrAdd(code, c => new Lazy<Currency>(() => new Currency(c, d))).Value;
    }

    public static int Count => Instances.Count;
}
Output
USD has 2 decimals
JPY has 0 decimals
same USD object: True
instances: 2
XYZ: unknown currency
8 threads ask for EUR: 1 object
instances: 3
  • Verdict: stdlib. ConcurrentDictionary.GetOrAdd adds one value per key, but its factory may run more than once when threads race. A Lazy<T> as the value makes the creation run once.
  • When an extra object is harmless and only one must be kept, GetOrAdd with a plain factory is enough: only one key and value pair is added to the dictionary.
JavaScriptGitHub
const DECIMALS = new Map([["USD", 2], ["EUR", 2], ["JPY", 0]]); // the valid keys

class Currency {
  static #instances = new Map();
  static #creating = false;

  constructor(code, decimals) {
    if (!Currency.#creating) throw new TypeError("use Currency.of(code)");
    this.code = code;
    this.decimals = decimals;
    Object.freeze(this);
  }

  static of(code) {
    let instance = Currency.#instances.get(code);
    if (instance === undefined) {
      if (!DECIMALS.has(code)) throw new RangeError(code);
      Currency.#creating = true;
      try {
        instance = new Currency(code, DECIMALS.get(code));
      } finally {
        Currency.#creating = false;
      }
      Currency.#instances.set(code, instance); // one instance per key
    }
    return instance;
  }

  static get count() {
    return Currency.#instances.size;
  }
}

console.log("USD has", Currency.of("USD").decimals, "decimals");
console.log("JPY has", Currency.of("JPY").decimals, "decimals");
console.log("same USD object:", Currency.of("USD") === Currency.of("USD"));
console.log("instances:", Currency.count);
try {
  Currency.of("XYZ");
} catch (e) {
  console.log(`${e.message}: unknown currency`);
}
const seen = new Set(Array.from({ length: 8 }, () => Currency.of("EUR")));
console.log("8 calls ask for EUR:", seen.size, "object");
console.log("instances:", Currency.count);
Output
USD has 2 decimals
JPY has 0 decimals
same USD object: true
instances: 2
XYZ: unknown currency
8 calls ask for EUR: 1 object
instances: 3
  • Verdict: idiom. A static private Map holds the instances. JavaScript runs one thread per agent, so the check and the insert need no lock.
  • Symbol.for(key) is a multiton in the language: it returns the same symbol from the global symbol registry for the same key.
  • A WeakRef in the map, with a FinalizationRegistry to remove dead entries, keeps the registry from growing for ever.
TypeScriptGitHub
type Code = "USD" | "EUR" | "JPY";
const DECIMALS: Record<Code, number> = { USD: 2, EUR: 2, JPY: 0 }; // the valid keys

class Currency {
  private static readonly instances = new Map<Code, Currency>();
  readonly code: Code;
  readonly decimals: number;

  private constructor(code: Code) {
    this.code = code;
    this.decimals = DECIMALS[code];
  }

  static of(code: Code): Currency {
    let instance = Currency.instances.get(code);
    if (instance === undefined) {
      instance = new Currency(code);
      Currency.instances.set(code, instance); // one instance per key
    }
    return instance;
  }

  static parse(text: string): Currency | undefined {
    return Object.hasOwn(DECIMALS, text) ? Currency.of(text as Code) : undefined;
  }

  static get count(): number {
    return Currency.instances.size;
  }
}

console.log("USD has", Currency.of("USD").decimals, "decimals");
console.log("JPY has", Currency.of("JPY").decimals, "decimals");
console.log("same USD object:", Currency.of("USD") === Currency.of("USD"));
console.log("instances:", Currency.count);
console.log(`XYZ: ${Currency.parse("XYZ") === undefined ? "unknown currency" : "found"}`);
const seen = new Set(Array.from({ length: 8 }, () => Currency.of("EUR")));
console.log("8 calls ask for EUR:", seen.size, "object");
console.log("instances:", Currency.count);
Output
USD has 2 decimals
JPY has 0 decimals
same USD object: true
instances: 2
XYZ: unknown currency
8 calls ask for EUR: 1 object
instances: 3
  • Verdict: idiom. A union type of the keys lets the compiler reject Currency.of("XYZ"). Text from outside goes through parse, which checks the key at run time.
  • When the set of keys is fixed and known at compile time, a frozen object of instances is simpler than a registry: the instances exist from the start, and no code creates them.
package main

import (
	"fmt"
	"sync"
)

type Currency struct {
	Code     string
	Decimals int
}

var (
	decimals  = map[string]int{"USD": 2, "EUR": 2, "JPY": 0} // the valid keys
	mu        sync.Mutex
	instances = map[string]*Currency{}
)

// Of returns the one *Currency for code.
func Of(code string) (*Currency, error) {
	d, ok := decimals[code]
	if !ok {
		return nil, fmt.Errorf("%s: unknown currency", code)
	}
	mu.Lock()
	defer mu.Unlock()
	c, ok := instances[code]
	if !ok {
		c = &Currency{Code: code, Decimals: d}
		instances[code] = c // one instance per key
	}
	return c, nil
}

func count() int {
	mu.Lock()
	defer mu.Unlock()
	return len(instances)
}

func main() {
	usd, _ := Of("USD")
	jpy, _ := Of("JPY")
	fmt.Println("USD has", usd.Decimals, "decimals")
	fmt.Println("JPY has", jpy.Decimals, "decimals")
	again, _ := Of("USD")
	fmt.Println("same USD object:", usd == again)
	fmt.Println("instances:", count())
	if _, err := Of("XYZ"); err != nil {
		fmt.Println(err)
	}

	var wg sync.WaitGroup
	var seenMu sync.Mutex
	seen := map[*Currency]bool{}
	for range 8 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			c, _ := Of("EUR")
			seenMu.Lock()
			seen[c] = true
			seenMu.Unlock()
		}()
	}
	wg.Wait()
	fmt.Println("8 goroutines ask for EUR:", len(seen), "object")
	fmt.Println("instances:", count())
}
Output
USD has 2 decimals
JPY has 0 decimals
same USD object: true
instances: 2
XYZ: unknown currency
8 goroutines ask for EUR: 1 object
instances: 3
  • Verdict: idiom. A package-level map behind a sync.Mutex is the registry, and a pointer is the identity. Go has no private constructor, so other packages could still build a Currency value; an unexported type with an exported interface closes that gap.
  • Go reports an unknown key with an error value in place of an exception.
RustGitHub
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::{Arc, LazyLock, Mutex};
use std::thread;

#[derive(Debug)]
pub struct Currency {
    pub code: &'static str,
    pub decimals: u32,
    _private: (), // no code outside this module can build one
}

const VALID: [(&str, u32); 3] = [("USD", 2), ("EUR", 2), ("JPY", 0)];

static INSTANCES: LazyLock<Mutex<HashMap<&'static str, Arc<Currency>>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

impl Currency {
    pub fn of(code: &str) -> Result<Arc<Currency>, String> {
        let &(code, decimals) = VALID
            .iter()
            .find(|(c, _)| *c == code)
            .ok_or_else(|| format!("{code}: unknown currency"))?;
        let mut map = INSTANCES.lock().unwrap();
        let c = map
            .entry(code)
            .or_insert_with(|| Arc::new(Currency { code, decimals, _private: () }));
        Ok(Arc::clone(c)) // one instance per key
    }

    pub fn count() -> usize {
        INSTANCES.lock().unwrap().len()
    }
}

fn main() {
    println!("USD has {} decimals", Currency::of("USD").unwrap().decimals);
    println!("JPY has {} decimals", Currency::of("JPY").unwrap().decimals);
    let same = Arc::ptr_eq(&Currency::of("USD").unwrap(), &Currency::of("USD").unwrap());
    println!("same USD object: {same}");
    println!("instances: {}", Currency::count());
    if let Err(e) = Currency::of("XYZ") {
        println!("{e}");
    }

    let handles: Vec<_> = (0..8)
        .map(|_| thread::spawn(|| Arc::as_ptr(&Currency::of("EUR").unwrap()) as usize))
        .collect();
    let seen: HashSet<usize> = handles.into_iter().map(|h| h.join().unwrap()).collect();
    println!("8 threads ask for EUR: {} object", seen.len());
    println!("instances: {}", Currency::count());
}
Output
USD has 2 decimals
JPY has 0 decimals
same USD object: true
instances: 2
XYZ: unknown currency
8 threads ask for EUR: 1 object
instances: 3
  • Verdict: stdlib. A LazyLock<Mutex<HashMap<_, Arc<_>>>> is the registry. Arc shares one object among the callers, and Arc::ptr_eq tests identity.
  • The entry API makes the check and the insert one call, and the Mutex makes that call safe across threads.
  • A private field stops other modules from building a Currency, so of is the only way to get one.

Consequences

The benefits:

  • Identity per key. Callers can compare instances with == or is, and two parts of the program that ask for the same key share one object and its state.
  • Validation in one place. The access method checks the key once. Java's Currency has no public constructor, and getInstance throws IllegalArgumentException if the code is not a supported ISO 4217 code.5
  • Lazy creation. An instance is created only when a caller first asks for its key.

The costs are those of Singleton, once for each key. A multiton is global state, and global state makes unit tests harder: one test can change an instance that the next test gets.1

The registry holds every instance for ever. In a language with garbage collection, the registry keeps a strong reference to each instance, so no instance is ever collected.1 This is harmless when the keys are a small fixed set, such as currencies. It is a leak when the keys come from input. Here each request uses a new key, and the registry keeps all of them:

This code runs but gives a wrong answer on purpose.

class Tag:
    _instances = {}

    @classmethod
    def of(cls, name):
        if name not in cls._instances:
            cls._instances[name] = cls()
        return cls._instances[name]


for i in range(100_000):
    Tag.of(f"request-{i}")  # a new key for each request
print("instances kept:", len(Tag._instances))
Output
instances kept: 100000

One fix is to validate the key against a fixed set, as the Currency example does. Another is to hold the instances weakly. Python's WeakValueDictionary discards an entry when no strong reference to the value exists any more.6 The weakref documentation gives this use: a cache or mapping that should not keep a large object alive only because the object is in the mapping.6

import weakref


class Tag:
    _instances = weakref.WeakValueDictionary()

    @classmethod
    def of(cls, name):
        tag = cls._instances.get(name)
        if tag is None:
            tag = cls()
            cls._instances[name] = tag
        return tag


for i in range(100_000):
    Tag.of(f"request-{i}")
print("instances kept:", len(Tag._instances))
admin = Tag.of("admin")
print("same object while in use:", admin is Tag.of("admin"))
print("instances kept:", len(Tag._instances))
Output
instances kept: 0
same object while in use: True
instances kept: 1

A weak registry changes the guarantee. There is one instance for each key while some code holds it. After the last holder lets go, the next request creates a new object, so any state in the old object is lost.

When not to use it

Do not use a multiton when the instances are values with no identity. If two Currency objects with the same code are equal by their fields, a Static factory method that returns a new or cached object, with an equality method, is enough.

Do not use it when the set of keys is fixed and known at compile time. An enum is simpler. In Java, an enum class has no instances other than those defined by its enum constants,7 so the language gives one instance per key with no registry.1

Do not use it to reach shared services from everywhere. Pass the instance that a component needs to the component. The registry then belongs to the code that builds the program, and tests can give each component its own instance.

Singleton. A multiton with one key is a Singleton pattern. An enum with one constant is the same in Java.1

Registry of singletons. In Design Patterns, the registry maps a name to the one instance of a subclass, so that the program can choose the class of its singleton by name, for example from an environment variable.2

Interning. The registry of a multiton can be in the language. Symbol.for(key) in JavaScript searches a runtime-wide symbol registry for the key, returns the symbol if it is there, and otherwise creates a new symbol in the registry.8

Flyweight. A Flyweight pattern factory also returns one shared object for each key. The difference is the purpose. A flyweight is immutable and saves memory when there are many equal objects. A multiton instance can have state, and its purpose is one identity for each key.

Object pool. An Object pool gives a client any free object, and takes it back after use. A multiton gives every client the same object for a key, and never takes it back.

Known uses

  • Java: java/util/Currency.java at jdk-25+36. The class keeps a static ConcurrentMap named instances. getInstance returns the entry for the code if there is one. If not, it checks the code, builds a new Currency and stores it with putIfAbsent, so that two threads that race get the same object.9 The API documentation says that there is never more than one Currency instance for any given currency.5
  • Python: Lib/logging/init.py at v3.14.0. Manager.getLogger takes the module lock, looks up the name in loggerDict, and creates and stores a new Logger if the name is not there.10 The documentation says that multiple calls to getLogger() with the same name will always return a reference to the same Logger object.11

References

  1. Multiton pattern, Wikipedia, Introduction; Description; Drawbacks; Implementations
  2. Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Singleton, Implementation (subclassing the Singleton class, a registry of singletons) and Consequences
  3. ConcurrentHashMap, Java SE 25 API, computeIfAbsent
  4. ConcurrentDictionary<TKey,TValue>.GetOrAdd Method, .NET API reference, Remarks
  5. Currency, Java SE 25 API, Class description; getInstance(String)
  6. weakref, The Python Standard Library, Python 3.14, Introduction; WeakValueDictionary
  7. The Java Language Specification, Java SE 25 Edition, 8.9 Enum Classes
  8. Symbol.for(), MDN Web Docs, Introduction; Description
  9. OpenJDK jdk-25+36 source, java/util/Currency.java, getInstance(String, int, int), lines 303 to 355; the instances map, line 144
  10. CPython v3.14.0 source, Lib/logging/__init__.py, Manager.getLogger, lines 1362 to 1391
  11. logging, The Python Standard Library, Python 3.14, logging.getLogger

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/Z2NCVX/text.yaml