Video in progress

Strong Middle 🧭 Design patterns

What is the Flyweight pattern, where is it used in the JDK, and what trap does it lead to?

Flyweight saves memory by sharing identical, immutable state among many objects: the object isn't created again, it's returned from a cache. In the JDK, the Integer.valueOf cache, string literals and enums work this way. The trap is that comparing such objects with == works sometimes and fails other times.

📖 Answer

The idea: you split an object's state in two. The intrinsic part is the same for everyone and never changes, so it is stored in a single instance. The extrinsic part is specific to each use, and the caller supplies it.

Example: 2 million order lines, each with a product name, category and image URL. But there are only 5,000 distinct products. Instead of creating a separate ProductInfo for every line, you keep a reference to one shared instance, and the heap shrinks several times over.

In the JDK:

  • Integer.valueOf and Long.valueOf cache the range -128..127; Boolean.valueOf always returns one of two objects;
  • string literals live in the string pool as a single instance;
  • enum constants are ideal flyweights.

The classic trap:

Integer a = 127, b = 127;
System.out.println(a == b);   // true — from the cache
Integer c = 1000, d = 1000;
System.out.println(c == d);   // false — two different objects

In tests, everything passes with small ids; on prod the condition breaks once an id goes above 128. Always compare wrapper types with equals.

Flyweight requires the intrinsic state to be immutable. If anyone modifies a shared object, the change spreads to every place that uses it.