Flyweight

November 27, 20269 minutes

A map app with 100,000 pins crashes because every pin carries its own copy of an icon. Learn how Flyweight splits shared state from per-object state, and when it isn't worth it.

Your map app plots a hundred thousand pins: cafes, fuel stops, charging points, pharmacies and parks. In the code, every pin is an object, and each one carries its own copy of the icon bitmap, the colour, and the label font. One cafe icon is about twenty kilobytes, so a hundred thousand copies come to about two gigabytes (an estimate, derived below). The app slows down, and then it crashes on older phones. Most of those copies are identical. There’s a pattern for exactly this, and it’s called Flyweight.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

A hundred thousand pins

Each Pin holds its position and label, plus an icon, a colour and a font that depend only on the kind of pin (cafe, fuel, charge, pharmacy, park). The position and label differ for every pin. The icon, colour and font are the same for every pin of a kind, and that is the part we are paying for over and over.

A rubber stamp

Think of a rubber stamp and an ink pad. The stamp holds the design, say a little paw print. Press it on paper, and you get an impression. Now stamp a thousand pages. You don’t carve a thousand stamps. One stamp makes every impression, and the impressions only record where each one landed.

So the design is shared, and the position is different every time. Keep the stamps in a drawer, one per design. Need a paw print? Take it from the drawer. Carve a new stamp only for a design you don’t have yet.

In code, the stamp is the flyweight. The drawer is the factory. And where you pressed it is state that you pass in.

The obvious version

Here’s the obvious version. A pin holds its position and its label. And it loads its own icon, colour and font for its kind. (Canvas, Bitmap, Icons, Colors and Fonts are made-up helpers; Bitmap is assumed to be immutable.)

public final class Pin {
    private final double lat;
    private final double lon;
    private final String label;
    private final Bitmap icon;
    private final int color;
    private final String font;

    public Pin(double lat, double lon, String label, String kind) {
        this.lat = lat;
        this.lon = lon;
        this.label = label;
        this.icon = Icons.load(kind);
        this.color = Colors.of(kind);
        this.font = Fonts.of(kind);
    }

    public void draw(Canvas canvas) {
        canvas.icon(icon, lat, lon, color);
        canvas.text(label, lat, lon, font);
    }
}

Drawing is simple: put the icon at the position, then write the label beside it. For a hundred pins, that’s fair. Each pin is self-contained, and easy to read. Nothing here is wrong. It just doesn’t scale.

Why it breaks

Two cafe pins carry two copies of the same icon, the same colour and the same font. Now count: a hundred thousand pins, times twenty kilobytes for the icon, is about two gigabytes.

Estimate. Assume a small icon bitmap of about 20 KB. 100,000 × 20 KB = 2,000,000 KB, roughly 2 GB. The colour and the font reference are tiny next to the bitmap. Real sizes depend on the JVM and the image format; the order of magnitude is the point.

Pins come in only five kinds. That means five different icons, and a hundred thousand copies of them. Loading is slow too, because every new pin reads its icon again. The waste isn’t the pins. It’s the same data, stored over and over.

Before and after for three pins. Before: two cafe pins and one fuel pin each hold their own icon, colour and font. After: the same three pins hold only lat, lon and label, and point at two shared styles, PinStyle cafe and PinStyle fuel. Before and after for three pins. Before: two cafe pins and one fuel pin each hold their own icon, colour and font. After: the same three pins hold only lat, lon and label, and point at two shared styles, PinStyle cafe and PinStyle fuel.
The icon stops being copied. It is shared.

Intrinsic and extrinsic: the key idea

So split each pin’s state in two. Some of it is the same for every pin of a kind: the icon, the colour and the font. We call that intrinsic state. The rest is different for every pin: latitude, longitude, and the label text. That’s extrinsic state.

Share the intrinsic part, so there’s one cafe style and a hundred thousand pins pointing at it. Keep the extrinsic part with each pin, or pass it in when you draw.

A pin's state split in two. Intrinsic state (icon, colour, font) is shared: one style per kind. Extrinsic state (latitude, longitude, label) stays with each pin or is passed in when drawing. A pin's state split in two. Intrinsic state (icon, colour, font) is shared: one style per kind. Extrinsic state (latitude, longitude, label) stays with each pin or is passed in when drawing.
Share what's the same. Pass in what's different.

The Gang of Four put it this way (Design Patterns, 1994): use sharing to support large numbers of fine-grained objects efficiently.

Share what’s the same. Pass in what’s different.

Building it

Start with the shared part. PinStyle is a record, holding the kind, the icon, the colour and the font. Its draw method receives the position and the label.

public record PinStyle(String kind, Bitmap icon, int color, String font) {
    public void draw(Canvas canvas, double lat, double lon, String label) {
        canvas.icon(icon, lat, lon, color);
        canvas.text(label, lat, lon, font);
    }
}

Next, the drawer. PinStyles keeps a map from kind to style. Its of method asks the map to compute the style if it’s absent. The first cafe pin creates the cafe style. Every other cafe pin finds it in the map, and reuses it. (ConcurrentHashMap.computeIfAbsent is performed atomically, and the function is invoked once per call if the key is absent, according to its Javadoc. The computation should be short and simple.)

public final class PinStyles {
    private static final Map<String, PinStyle> CACHE = new ConcurrentHashMap<>();

    private PinStyles() {}

    public static PinStyle of(String kind) {
        return CACHE.computeIfAbsent(kind, k ->
                new PinStyle(k, Icons.load(k), Colors.of(k), Fonts.of(k)));
    }
}

Now the pin itself. It keeps its latitude, longitude and label, and a reference to the shared style. The constructor gets that style from the drawer. Drawing hands the position and the label to the style, and the style supplies the icon, the colour and the font.

public final class Pin {
    private final double lat;
    private final double lon;
    private final String label;
    private final PinStyle style;

    public Pin(double lat, double lon, String label, String kind) {
        this.lat = lat;
        this.lon = lon;
        this.label = label;
        this.style = PinStyles.of(kind);
    }

    public void draw(Canvas canvas) {
        style.draw(canvas, lat, lon, label);
    }
}

Make two cafe pins and ask for the cafe style twice. It’s the same object.

Pin north = new Pin(45.5, -73.6, "Cafe Nord", "cafe");
Pin south = new Pin(45.4, -73.7, "Cafe Sud", "cafe");
PinStyle a = PinStyles.of("cafe");
PinStyle b = PinStyles.of("cafe");
// a == b: one style per kind

Now redo the sum.

Estimate. Five styles at 20 KB each is about 100 KB. A Pin object (header, two doubles, two references) is roughly 40 bytes, and its label string adds perhaps 60 more, so about 100 bytes per pin: 100,000 pins come to roughly 10 MB. That is about 200 times smaller than 2 GB. Again, a rough figure, not a measurement.

Roles and rules

The pattern has four roles. The flyweight is PinStyle. The factory is PinStyles. The context is Pin, which holds the extrinsic state. And the client builds and draws the pins.

Class diagram of Flyweight. PinStyles (the factory, with of(kind)) creates and keeps PinStyle records (the flyweight, with draw). Pin (the context, holding lat, lon and label) uses a shared PinStyle. Class diagram of Flyweight. PinStyles (the factory, with of(kind)) creates and keeps PinStyle records (the flyweight, with draw). Pin (the context, holding lat, lon and label) uses a shared PinStyle.
Factory, flyweight, context.

Four rules keep it safe:

  1. A flyweight must be immutable. If the style had a setter, changing it for one pin would repaint every cafe pin. A record has no setters, and the bitmap inside has to be immutable too. (refactoring.guru: set the state once through the constructor, with no setters or public fields.)
// if PinStyle had a public color field
PinStyles.of("cafe").color = 0xFF0000;
  1. The factory is the only way in. If code calls the style constructor directly, the duplicates come back.
  2. The same kind gives the same object. So compare styles by their kind, and don’t build logic on object identity.
  3. The price. The extrinsic state travels on every call, and the code gets harder to follow. You trade some clarity for memory (refactoring.guru also notes it may trade memory for CPU time when context must be recomputed).

In the JDK: boxed integers

The JDK shares objects too. Integer.valueOf always caches the numbers from -128 up to 127; the Javadoc says it “will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range”. And the Java Language Specification (section 5.1.7, boxing conversion) requires that boxing a small constant gives the same object each time.

Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(c.equals(d));

So boxing 127 twice gives the same object, so a == b is true. Boxing 128 twice need not, so c == d isn’t guaranteed (on typical JVMs it is false). Compare boxed numbers with equals.

The same idea shows up elsewhere. String.intern returns one canonical string from a pool (its Javadoc: s.intern() == t.intern() exactly when s.equals(t)). And Boolean.valueOf hands back the shared Boolean.TRUE and Boolean.FALSE objects.

The mix-ups

A common mix-up: Flyweight is just caching. A cache saves work, because it keeps an answer you would otherwise compute again. A flyweight saves memory. It shares immutable state, and moves the rest out of the object. The factory looks like a cache, but the split is the difference.

Singleton hands out one shared object too. But a singleton is one instance overall, and it may be mutable. A flyweight factory holds one immutable instance per key. Prototype is the opposite move: it copies an object to make a new one, while Flyweight shares an object so you don’t need the copy. And in a composite tree, many leaves are often identical, so they can be flyweights too.

PatternWhat it does with objects
Singletonone instance overall; may be mutable
Prototypecopies an object to make a new one
Flyweightone immutable instance per key, shared

When not to use it

Skip it if you only have a few objects, a few hundred or a few thousand: memory isn’t the problem. If most of each object’s state is unique, there’s little to share. The pins worked because five icons covered a hundred thousand pins. And measure first. Profile the memory, find the duplicated data, and only then share it. Without a measured problem, you just add complication.

Decision flowchart. Many similar objects? No: skip it. Yes: measured a memory problem? No: measure first. Yes: is much of the state identical across objects? No: little to share, skip. Yes: can the shared part be immutable? No: make it immutable or skip. Yes: use Flyweight. Decision flowchart. Many similar objects? No: skip it. Yes: measured a memory problem? No: measure first. Yes: is much of the state identical across objects? No: little to share, skip. Yes: can the shared part be immutable? No: make it immutable or skip. Yes: use Flyweight.
Share only what repeats.

Remember the costs: an extra lookup, extrinsic state passed on every call, and code that’s harder to follow.

Recap and checklist

A hundred thousand pins held a hundred thousand copies of just five icons. Split the state: intrinsic is shared, and extrinsic is passed in. A factory hands out one immutable flyweight per kind. It’s more than caching, you should measure before you use it, and the JDK’s small integer cache shows the same shape.

  • Is memory a measured problem, caused by many similar objects?
  • Is most of the duplicated state identical for a whole kind (intrinsic)?
  • Is the shared part immutable, all the way down (including fields like a bitmap)?
  • Does one factory hand out the instances, so there is one per key?
  • Is the extrinsic state small, or passed in cheaply?

Share what’s the same. Pass in what’s different.

Further reading: Gamma et al., Design Patterns (Flyweight); refactoring.guru’s Flyweight page; the Javadoc for Integer.valueOf, String.intern, Boolean.valueOf and ConcurrentHashMap.computeIfAbsent; JLS 5.1.7 (boxing conversion).