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.
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.
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.
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.
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.
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.
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.
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 kindNow redo the sum.
Estimate. Five styles at 20 KB each is about 100 KB. A
Pinobject (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.
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.
Four rules keep it safe:
// if PinStyle had a public color field
PinStyles.of("cafe").color = 0xFF0000;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.
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.
| Pattern | What it does with objects |
|---|---|
| Singleton | one instance overall; may be mutable |
| Prototype | copies an object to make a new one |
| Flyweight | one immutable instance per key, shared |
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.
Remember the costs: an extra lookup, extrinsic state passed on every call, and code that’s harder to follow.
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.
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).