# FlyweightA 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.

{{< lesson-video youtube="3rR1NZBMdqY" title="Flyweight" >}}

## 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.)

```java
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.

```mermaid {alt="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." caption="The icon stops being copied. It is shared."}
flowchart TB
  subgraph BEFORE["Before: every pin owns its style"]
    direction TB
    A1["Pin: cafe<br/>lat, lon, label,<br/>icon, colour, font"]
    A2["Pin: cafe<br/>lat, lon, label,<br/>icon, colour, font"]
    A3["Pin: fuel<br/>lat, lon, label,<br/>icon, colour, font"]
  end
  subgraph AFTER["After: pins share a style per kind"]
    direction TB
    B1["Pin: cafe<br/>lat, lon, label"] --> S1["PinStyle cafe<br/>icon, colour, font"]
    B2["Pin: cafe<br/>lat, lon, label"] --> S1
    B3["Pin: fuel<br/>lat, lon, label"] --> S2["PinStyle fuel<br/>icon, colour, font"]
  end
  BEFORE ~~~ AFTER
  class A1,A2,A3 bad
  class B1,B2,B3 c1
  class S1,S2 c6
```

## 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.

```mermaid {alt="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." caption="Share what's the same. Pass in what's different."}
flowchart LR
  P["a pin's state"] --> I["intrinsic: icon, colour, font<br/>the same for every pin of a kind"]
  P --> E["extrinsic: lat, lon, label<br/>different for every pin"]
  I --> SH["shared: one PinStyle per kind"]
  E --> PA["kept per pin, or passed in<br/>when drawing"]
  class P hl
  class I,SH c6
  class E,PA warn
```

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.

```java
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.)

```java
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.

```java
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.

```java
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.

```mermaid {alt="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." caption="Factory, flyweight, context."}
classDiagram
  class PinStyles {
    +of(kind) PinStyle
  }
  class PinStyle {
    <<record>>
    +kind
    +icon
    +color
    +font
    +draw(canvas, lat, lon, label)
  }
  class Pin {
    -lat
    -lon
    -label
    -style
    +draw(canvas)
  }
  PinStyles ..> PinStyle : creates and keeps
  Pin --> PinStyle : uses, shared
```

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.)

```java
// if PinStyle had a public color field
PinStyles.of("cafe").color = 0xFF0000;
```

2. **The factory is the only way in.** If code calls the style constructor directly, the duplicates
   come back.
3. **The same kind gives the same object.** So compare styles by their kind, and don't build logic
   on object identity.
4. **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.

```java
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](/patterns/singleton-pattern/) 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](/patterns/prototype-pattern/) 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](/patterns/composite-pattern/) 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 |

## 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.

```mermaid {alt="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." caption="Share only what repeats."}
flowchart TD
  Q1{"Many similar objects?"} -- no --> N1["Skip it"]
  Q1 -- yes --> Q2{"Measured a memory problem?"}
  Q2 -- no --> N2["Measure first"]
  Q2 -- yes --> Q3{"Is much of the state<br/>identical across objects?"}
  Q3 -- no --> N3["Little to share: skip"]
  Q3 -- yes --> Q4{"Can the shared part<br/>be immutable?"}
  Q4 -- no --> N4["Make it immutable, or skip"]
  Q4 -- yes --> Y["Use Flyweight"]
  class N1,N2,N3,N4 bad
  class Y good
```

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).
