Creating objects properly: static factories, builders, singletons and why "only one instance" keeps breaking
A constructor makes the caller decide parameter order, whether a new object is created and which concrete class it is. When to move those decisions into a static factory, a builder or a container; what scope a singleton really has and four ways to break one; needless objects, obsolete references, Cleaner instead of finalize; how to review AI-written builders and singletons.
On this page
1. The problem
OrderNumberGenerator is a hand-written singleton holding an AtomicLong loaded from max(order_no) at startup. The service scales from 1 to 3 pods; on day one there are 37 pairs of orders with the same number. Not one line changed, tests still pass.
2. Key idea
Creating an object involves a few hidden decisions. A constructor hands most of them to the caller, and nobody says what scope "only one" means. Move each decision to whoever knows best: the class knows its rules, the container knows lifecycles, the database knows "unique across the cluster".
| Approach | Use when | Don't use when |
|---|---|---|
| Constructor | a few parameters of different types; frameworks need it (JPA, Jackson) | many same-typed parameters: swapping adults and children still compiles |
| Static factory | you need a name, caching, a hidden subclass, an Optional |
the class is designed for inheritance |
| Builder | about four or more parameters, many optional | a record with 2–4 clear fields |
| Spring bean (singleton) | you have Spring and need injection and mocks | "unique" must hold across pods |
| Single-value enum, holder idiom | outside a container: immutable lookup tables | it has dependencies you swap in tests |
| DB sequence | unique across the cluster: order and invoice numbers | unique within one process is enough |
2.1 Where do singletons break?
- A
privateconstructor +staticfield only blocksnew. Reflection, serialization,clone()and multiple ClassLoaders still create a second one; an enum blocks the first three. - A Spring singleton bean is "one per container", not one per cluster.
- A singleton bean is shared across threads: keep no per-request mutable state in it.
2.2 Are extra objects a worry?
Object creation in Java is cheap; worry only on hot paths: 200 million additions take 302 ms with Long sum and 54 ms with long sum. Build Pattern and ObjectMapper once and reuse them. A real leak is a hand-managed array that never nulls out slots it removed.
3. In Java
// Static factory: named, returns an existing object
public static Money of(BigDecimal amount, String currency) {
if (amount.signum() == 0 && currency.equals("VND")) return ZERO_VND;
return new Money(amount, currency);
}
// Builder: required in builder(), optional by name, rules in build()
FlightSearch s = FlightSearch.builder("HAN", "DAD", LocalDate.of(2026, 12, 20))
.returnOn(LocalDate.of(2026, 12, 24))
.adults(2).children(1)
.build(); // from == to or return before departure -> IllegalArgumentException
// Lazy singleton outside Spring: holder idiom, no locks
public final class Lazy {
private Lazy() {}
private static final class Holder { static final Lazy INSTANCE = new Lazy(); }
public static Lazy get() { return Holder.INSTANCE; } // created on the first get()
}Other languages: Go uses NewX functions and sync.Once; Kotlin and Python have named arguments, so builders are rarer; a Node.js module is a singleton per process.
4. Working with AI
Give the AI: builders with tests for every rule; finding every getInstance(), stateful static field and finalize() in the repo.
Check in AI-written code:
-
build()copies every collection (List.copyOf); reusing a builder doesn't change built objects. - Cross-field rules live in
build()or a compact constructor. - No hand-written singletons when Spring is present.
- Cluster-wide unique values come from the database, not an in-memory counter.
- No new
finalize()orclone(); resources close via try-with-resources.
5. Exercises
Exercise 1: An "immutable" builder
The AI says: "FlightSearch is immutable and the builder can be reused for many searches".
private FlightSearch(Builder b) {
this.from = b.from; this.to = b.to; this.adults = b.adults;
this.airlines = b.airlines;
}
public FlightSearch build() {
if (adults < 1) throw new IllegalArgumentException("adults >= 1");
return new FlightSearch(this);
}Find the bug, write a test proving it, fix it.
Solution to Exercise 1
The object and the builder share one ArrayList. Reusing the builder changes objects already built:
var b = FlightSearch.builder("HAN", "SGN", d).airline("VN");
FlightSearch first = b.build();
b.airline("VJ");
assertEquals(List.of("VN"), first.airlines()); // red: [VN, VJ]Fix: this.airlines = List.copyOf(b.airlines). Second bug: build() misses cross-field rules: from == to, return before departure, more than 2 children per adult. Check them all and report every error at once.
Exercise 2: Where order numbers come from
Back to section 1. The AI offers: (A) keep the singleton, rewritten with the holder idiom and an AtomicLong; (B) a Spring bean calling nextval('order_no_seq'). Pick one for 3 pods; when is A still acceptable?
Solution to Exercise 2
Pick B. A fixes a bug that doesn't exist (initialization was already thread-safe) and ignores the real one: each pod is a JVM with its own AtomicLong, all loading the same max and incrementing together. A sequence is the cluster-wide source of uniqueness; a bean wraps the call so it can be mocked.
A is fine with a single process (batch job, CLI), or when each node has an id baked into the number (Snowflake-style). Sequences have gaps (rollbacks lose numbers): don't use them when rules demand gapless invoice numbers.
Summary
- Static factories have names and can return cached objects or hidden subclasses.
- Builders for many optional parameters; rules in
build(), collections always copied. - In Spring a singleton is a bean; outside it, use the holder idiom or an enum.
- "Unique across the cluster" belongs to the database.
- No
finalize, noclone: try-with-resources and copy constructors.
Read more: Immutable objects, equals and hashCode.
Practice interview questions on this topic
- What is the Prototype pattern? How do shallow and deep copies differ?
- How do you write a thread-safe singleton, how can it be broken, and how does Spring's singleton differ?
- When do you use a static factory method or a Builder instead of a constructor?
- Why avoid clone(), finalize() and Java serialization, and what should you use instead?
Comments
Community rules