AlgoViz

Singleton

medium 60 min

One object and one way to reach it.

Watch lesson4:52

Problem

Copies that drift, and what exactly must be guaranteed.

The point: say what must be one, and one per what, before you write a static field.

The task

What we are asked

The first minute

  1. Interviewer

    Our program has an auth part, a payment part and an analytics part. They all need the configuration. Design the configuration manager.

  2. You

    Is this one process with three parts, or three services in three processes?

  3. Interviewer

    Good question. One process.

  4. You

    Then one object in memory is enough. I will guarantee that it is built once, also with many threads, and that readers always see complete values. If they were separate services, each process would have its own object, and I would need a shared source and a way to announce changes.

From words to guarantees

RequirementGuaranteeHow
All parts decide by the same valuesOne objectPrivate constructor, one door
Reading the file is slowBuilt at most onceLazy with a lock, or eager
Eight request threadsNo two builders, no half-built objectSecond check, safe publication
Operations may move the databaseLater readers see the new addressVolatile or locked field
Unknown keyLoud errorException with the name

The design that hurts: one each

AuthService- config: ConfigPaymentService- config: ConfigAnalyticsService- config: Config

1/3Each part is independent

That sounds good, and for most things it is.

owns (dies together)

Objects drawn as classes here, to show the copies side by side.