GoF patterns plus concurrency, architectural, and resilience patterns, with when-to-use guidance, code, and common pitfalls.
Preview — first 3 of 112 cards
Singleton
One instance with global access, created at startup or on first use. Legitimate for process-wide, effectively stateless infrastructure (config snapshot, metrics registry); it becomes an anti-pattern when it holds mutable state or hides dependencies. Prefer injecting one instance behind an interface — same lifetime, testable, and DIP-compliant.
public enum Config {
INSTANCE;
private final Map<String, String> values = Map.of("region", "eu-west-1");
public String get(String key) { return values.get(key); }
}
Thread-safe singleton in Java
Three safe options: enum (serialization/reflection safe, simplest), static holder idiom (lazy, no locking on reads), or volatile double-checked locking. Avoid synchronizing the whole getter — it serializes every read.
final class Registry {
private Registry() {}
private static final class Holder { static final Registry INSTANCE = new Registry(); }
static Registry get() { return Holder.INSTANCE; }
}
Double-checked locking without volatile
Without volatile, the reference can become visible before the constructor's writes: another thread sees a non-null object with default fields (unsafe publication). Writing `synchronized { ... }` does not compile either — synchronized needs a monitor, e.g. synchronized (Singleton.class). Fix with volatile, the holder idiom, or an enum.
private static volatile Singleton instance; // volatile is required
public static Singleton get() {
if (instance == null) {
synchronized (Singleton.class) { // lock required
if (instance == null) instance = new Singleton();
}
}
return instance;
}
109 more cards in this sheet
Unlock the System Design bundle — ₹399
One-time payment. Unlocks this sheet and 10 other sheets in the bundle, plus a typeset PDF of each.
Unlock the bundle
See all bundles
Or get all 76 sheets for ₹999 — one payment, every future sheet included.