LOW-LEVEL DESIGN · STRUCTURAL PATTERNS · STRUCTURAL · 32 OF 48

Flyweight Pattern in Java: Share State to Save Memory at Scale

The Flyweight pattern through a 60,000-seat stadium map: intrinsic state shared in four immutable SeatStyle objects, extrinsic state kept in compact arrays and passed in, a thread-safe factory, the memory maths, the Integer cache, Flyweight vs Singleton and object pools, and where it appears in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 161 lines, with a small main() demo. Save it as StadiumSeatMapDemo.java, then run javac StadiumSeatMapDemo.java && java StadiumSeatMapDemo.

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Flyweight: a 60,000-seat stadium map shares four SeatStyle objects instead of 60,000 copies.
 * First the naive FatSeat (the problem), then the shared style, its factory and the SeatMap context.
 */
public class StadiumSeatMapDemo {

    static final int ICON_BYTES = 2048;

    // ---------- the problem: every seat carries its own copy of the heavy, repeated data ----------
    /** Naive seat. Sixty thousand of these hold sixty thousand copies of only four icons. */
    static final class FatSeat {
        final int row;
        final int number;
        boolean sold;
        final String tier;
        final String colourHex;
        final byte[] icon = new byte[ICON_BYTES];   // a private copy, every single time
        final String perks;

        FatSeat(int row, int number, String tier, String colourHex, String perks) {
            this.row = row;
            this.number = number;
            this.tier = tier;
            this.colourHex = colourHex;
            this.perks = perks;
        }
    }

    // ---------- the flyweight: intrinsic state only, immutable, shared ----------
    static final class SeatStyle {
        private final String tier;
        private final String colourHex;
        private final byte[] icon;
        private final String perks;

        private SeatStyle(String tier, String colourHex, byte[] icon, String perks) {
            this.tier = tier;
            this.colourHex = colourHex;
            this.icon = icon.clone();   // copy in, never hand out: nobody can change shared pixels
            this.perks = perks;
        }

        /** Extrinsic state (row, number, sold) arrives as arguments. It is never stored here. */
        String tooltip(int row, int number, boolean sold) {
            return tier + " row " + row + " seat " + number + " (" + perks + ", " + colourHex + ", icon "
                    + icon.length + " B)" + (sold ? " SOLD" : "");
        }

        char glyph(boolean sold) { return sold ? 'x' : tier.charAt(0); }
    }

    // ---------- the factory: exactly one SeatStyle per tier, safe under many threads ----------
    static final class SeatStyleFactory {
        private final Map<String, SeatStyle> cache = new ConcurrentHashMap<>();
        private final AtomicInteger loads = new AtomicInteger();

        SeatStyle styleFor(String tier) { return cache.computeIfAbsent(tier, this::load); }

        private SeatStyle load(String tier) {
            loads.incrementAndGet();
            byte[] icon = new byte[ICON_BYTES];   // pretend we decoded a PNG here
            return switch (tier) {
                case "Platinum" -> new SeatStyle(tier, "#e5e4e2", icon, "lounge access");
                case "Gold" -> new SeatStyle(tier, "#d4a017", icon, "free water");
                case "Silver" -> new SeatStyle(tier, "#c0c0c0", icon, "standard");
                case "Accessible" -> new SeatStyle(tier, "#1e90ff", icon, "step-free entry");
                default -> throw new IllegalArgumentException("unknown tier " + tier);
            };
        }

        int distinctStyles() { return cache.size(); }

        int loads() { return loads.get(); }
    }

    // ---------- the context: extrinsic state in compact arrays, plus a shared style per seat ----------
    static final class SeatMap {
        private final int perRow;
        private final short[] rows;
        private final short[] nums;
        private final boolean[] sold;
        private final SeatStyle[] style;

        SeatMap(int rowCount, int perRow, SeatStyleFactory factory) {
            this.perRow = perRow;
            int n = rowCount * perRow;
            rows = new short[n];
            nums = new short[n];
            sold = new boolean[n];
            style = new SeatStyle[n];
            for (int r = 1; r <= rowCount; r++) {
                SeatStyle tierStyle = factory.styleFor(tierForRow(r));
                for (int s = 1; s <= perRow; s++) {
                    int i = index(r, s);
                    rows[i] = (short) r;
                    nums[i] = (short) s;
                    style[i] = tierStyle;   // a reference, not a copy
                }
            }
        }

        static String tierForRow(int row) {
            if (row <= 30) return "Platinum";
            if (row <= 120) return "Gold";
            if (row <= 280) return "Silver";
            return "Accessible";
        }

        private int index(int row, int number) { return (row - 1) * perRow + (number - 1); }

        int size() { return rows.length; }

        void sell(int row, int number) { sold[index(row, number)] = true; }

        String tooltip(int row, int number) {
            int i = index(row, number);
            return style[i].tooltip(rows[i], nums[i], sold[i]);
        }

        String drawRow(int row, int from, int to) {
            StringBuilder sb = new StringBuilder();
            for (int s = from; s <= to; s++) sb.append(style[index(row, s)].glyph(sold[index(row, s)]));
            return sb.toString();
        }
    }

    public static void main(String[] args) {
        System.out.println("Before: two FatSeats in the same tier");
        FatSeat a = new FatSeat(40, 1, "Gold", "#d4a017", "free water");
        FatSeat b = new FatSeat(40, 2, "Gold", "#d4a017", "free water");
        System.out.println("  separate icon copies? " + (a.icon != b.icon)
                + " (" + a.icon.length + " B each, for seats " + a.number + " and " + b.number + ")");

        System.out.println("After: a flyweight seat map");
        SeatStyleFactory factory = new SeatStyleFactory();
        SeatMap map = new SeatMap(300, 200, factory);
        map.sell(29, 4);
        map.sell(31, 5);
        System.out.println("  seats: " + map.size() + ", SeatStyle objects: " + factory.distinctStyles()
                + ", icon loads: " + factory.loads());
        for (int r = 28; r <= 32; r++) System.out.println("  row " + r + "  " + map.drawRow(r, 1, 12));
        System.out.println("  " + map.tooltip(29, 4));
        boolean sameGold = factory.styleFor("Gold") == factory.styleFor("Gold");
        System.out.println("  same Gold object every time? " + sameGold);

        long naive = (long) map.size() * ICON_BYTES;
        long shared = (long) factory.distinctStyles() * ICON_BYTES + (long) map.size() * (2 + 2 + 1 + 4);
        System.out.printf("  approx memory: naive %.1f MB, flyweight %.2f MB%n", naive / 1e6, shared / 1e6);

        System.out.println("Java's own flyweight: the Integer cache");
        System.out.println("  valueOf(127) shared:  " + (Integer.valueOf(127) == Integer.valueOf(127)));
        System.out.println("  valueOf(1000) shared: " + (Integer.valueOf(1000) == Integer.valueOf(1000))
                + " (default JVM settings)");
        Integer big = 1000;
        System.out.println("  equals is always right: " + big.equals(Integer.valueOf(1000)));
    }
}

Notes

The problem

Here is the naive design. Each FatSeat holds its row, number and sold flag, and also its tier name, colour, a two kilobyte icon and a perks line. But there are only four tiers. So sixty thousand seats store sixty thousand copies of just four icons. That is about one hundred and twenty megabytes of duplicates, on a phone, for one screen. Garbage collection slows down and older phones run out of memory.

One object per seat
final class FatSeat {
  int row, number;
  boolean sold;
  String tier;      // "Gold"
  String colourHex; // "#d4a017"
  byte[] icon;      // 2 KB image
  String perks;     // "free water"
}

60,000 seats x 2 KB icon
= about 120 MB of copies

The idea

The idea in one sentence: share the part that is the same, and keep the part that differs outside. The shared part is called intrinsic state. It is the same for many objects and never changes: tier, colour, icon and perks. The unique part is called extrinsic state: row, seat number and whether it is sold. The flyweight object holds only intrinsic state. Extrinsic state is stored elsewhere and passed in when needed.

Two kinds of state
  • intrinsic state:
  • same for many objects,
  • never changes
  • tier, colour, icon, perks
  • extrinsic state:
  • different for each object,
  • kept outside, passed in
  • row, number, sold

The structure

Four roles. SeatStyle is the flyweight: small, immutable and shared. SeatStyleFactory hands out styles and makes sure there is exactly one object per tier. SeatMap is the context: it keeps the per seat data, row, number and sold flag, plus a reference to the right shared style. BookingScreen is the client that draws the map. Only four SeatStyle objects ever exist, whatever the size of the stadium.

Participants
  • flyweight: SeatStyle
  • immutable, shared
  • factory: SeatStyleFactory
  • same object per key
  • context: SeatMap
  • per-seat arrays plus a
  • style reference per seat
  • client: BookingScreen

Code: the flyweight

In code, SeatStyle has only final fields: tier, colour, icon and perks. Nothing in it can change after creation, which is what makes sharing safe. Notice the tooltip method. It does not store the row, the number or the sold flag. They come in as arguments, every time. That is the core trick of the pattern: the shared object works on extrinsic state it is given, never on state it keeps.

SeatStyle
final class SeatStyle {
  private final String tier, colourHex;
  private final byte[] icon;
  private final String perks;

  String tooltip(int row, int number,
                 boolean sold) {
    return tier + " row " + row + " seat "
        + number + (sold ? " sold" : "");
  }
}

Code: the factory

The factory keeps a map from tier name to style. Ask for Gold the first time and it loads the icon and builds the object. Ask again and you get the very same object back. Using a ConcurrentHashMap with compute if absent means two threads asking for Gold at the same moment still end up sharing one instance. Callers must never call new SeatStyle themselves, or sharing quietly breaks.

SeatStyleFactory
final class SeatStyleFactory {
  private final Map<String, SeatStyle>
      cache = new ConcurrentHashMap<>();

  SeatStyle styleFor(String tier) {
    return cache.computeIfAbsent(
        tier, this::load);
  }
}

Code: the context

The SeatMap context stores the extrinsic state compactly, in plain arrays: a short for the row, a short for the seat number, a boolean for sold, and one reference to the shared style. To describe seat i, it reads that seat's values and passes them into the style. There is no Seat object here at all. A flyweight design often removes the per item object completely.

SeatMap
final class SeatMap {
  private final short[] rows, nums;
  private final boolean[] sold;
  private final SeatStyle[] style;

  String tooltip(int i) {
    return style[i].tooltip(rows[i],
        nums[i], sold[i]);
  }
}

Run-through

Follow one redraw. The booking screen asks the seat map for rows twenty eight to thirty two. For each seat, the map reads that seat's row, number and sold flag from its arrays, takes the style reference it got from the factory when the map was built, and passes the values in. Every Gold seat on screen is described by the same Gold object. Thousands of calls, four objects doing all the work.

The memory maths

Now the maths. Naive: sixty thousand seats times a two kilobyte icon is about one hundred and twenty megabytes. Flyweight: four styles at two kilobytes each is eight kilobytes, plus about nine bytes per seat for two shorts, a boolean and a reference. That is about half a megabyte in total, more than two hundred times smaller. Do this sum out loud in an interview. The pattern only pays off when the shared part is big and the count is high.

Do the sum
  • naive:
  • 60,000 x 2 KB icon
  • = about 120 MB
  • flyweight:
  • 4 styles x 2 KB = 8 KB
  • + 60,000 x ~9 bytes
  • (2 shorts, 1 boolean,
  • 1 reference)
  • = about 0.55 MB

Already in Java

Java uses this idea itself. Integer value of always returns a shared, cached object for values from minus one hundred and twenty eight to one hundred and twenty seven, and autoboxing calls value of. So two boxed one hundred twenty sevens are the same object, while two boxed one thousands are usually different objects. Boolean value of returns one of two shared constants, and string literals are shared through the string pool. This is also why boxed numbers are compared with equals.

The Integer cache
Integer a = Integer.valueOf(127);
Integer b = Integer.valueOf(127);
a == b   // true: same cached object

Integer c = Integer.valueOf(1000);
Integer d = Integer.valueOf(1000);
c == d   // false on a default JVM

// so compare boxed numbers
// with equals(), never ==

Immutability is a must

Because one object is shared by thousands of users, it must be immutable. Make every field final, add no setters, copy arrays when they come in and never hand them out, and create objects only through the factory. If someone could change the Gold colour on one seat, it would change on every Gold seat, and on every thread. Immutable flyweights need no locks at all.

Rules for a safe flyweight
  • • every field final
  • • no setters
  • • copy arrays in, never
  • hand them out
  • • create only via the factory
  • then any number of threads
  • can share it with no locks

When to use it

Use Flyweight when you have a huge number of objects, most of their state repeats, the repeated part is heavy, and memory is a real, measured problem. Do not use it for a few hundred objects or when little state is shared. The pattern has a cost: state is split across classes, there is a factory to go through, and the code is harder to read. Measure with a heap dump or a profiler first.

Use it or skip it
  • worth it when:
  • • a huge number of objects
  • • most of their state repeats
  • • the repeated part is heavy
  • • memory is a measured problem
  • not worth it when:
  • • a few hundred objects
  • • little state is shared
  • • the split state hurts
  • readability more than it saves

Flyweight vs others

How does it differ from its neighbours? A singleton has exactly one instance. A flyweight factory has one shared instance per key, here one per tier. An object pool, like a database connection pool, lends a mutable object to one user at a time and takes it back. A flyweight is immutable and used by many at the same time. And a plain cache stores results, while a flyweight factory is a cache whose values are shared building blocks.

Neighbours
  • Singleton:
  • exactly one instance
  • Flyweight:
  • one shared instance PER KEY
  • Object pool:
  • lends a mutable object to
  • one user at a time
  • Flyweight:
  • immutable, used by many
  • at the same time

In LLD interviews

In interviews, Flyweight comes up when the question pushes on scale. A movie or stadium booking system shares seat types instead of copying them per seat. A game shares one model and texture across thousands of bullets or tiles. A text editor keeps one object per font style, not per character. A chess server can use twelve shared piece objects for every game it hosts. The common mistake is giving the shared object a setter.

Where it shows up
  • • movie or stadium booking:
  • shared seat types
  • • games: bullets and tiles
  • share a model and texture
  • • text editor: one object per
  • font style, not per letter
  • • chess server: 12 shared
  • piece objects for all games
  • mistake: a mutable flyweight

Say it like this

How to say it. Each seat gets a shared SeatStyle per tier from a factory. Row, number and sold flag live in compact arrays inside SeatMap and are passed into the style when needed. Styles are immutable, so every thread can share them without locks. That takes the map from about one hundred and twenty megabytes to under one megabyte. Short, concrete, and it shows you did the maths.

In the interview
  • "Seats share one SeatStyle
  • per tier from a factory.
  • Row, number and sold flag
  • live in arrays in SeatMap
  • and are passed in. Styles
  • are immutable, so threads
  • share them freely. Memory
  • drops from ~120 MB to
  • under 1 MB."

Interview questions

What is the Flyweight pattern?

Flyweight saves memory when there are very many similar objects. The repeated, unchanging part of their state is moved into a small number of shared, immutable objects, and the part that differs per object is stored outside and passed in when needed.

What is the difference between intrinsic and extrinsic state?

Intrinsic state is the same for many objects and never changes, so it lives inside the shared flyweight, like a seat tier and its icon. Extrinsic state differs per object, like the row and seat number, so the context stores it and passes it into the flyweight methods.

Why must flyweights be immutable?

One instance is shared by many users and often many threads. If it could change, a change made for one user would silently affect all of them, and concurrent access would need locking. Final fields, no setters and defensive copies make sharing safe and lock-free.

How do you make a flyweight factory thread safe?

Keep the instances in a ConcurrentHashMap and create them with computeIfAbsent, which runs the creation once per key even when several threads ask at the same time. Make constructors private or package-private so callers cannot bypass the factory.

How is Flyweight different from an object pool?

A pool lends a mutable object, such as a database connection, to one user at a time and takes it back afterwards. A flyweight is immutable and used by many clients at the same time, and it is never returned because nobody owns it exclusively.

How is Flyweight different from Singleton?

A singleton guarantees exactly one instance of a class. A flyweight factory keeps one shared instance per distinct key, so there can be several instances of the class, such as one style per seat tier.

Why does comparing two Integer objects with == sometimes return true?

Integer.valueOf, which autoboxing uses, always returns cached shared objects for values from -128 to 127, so two boxed 127s are the same object. Larger values are usually new objects, so == compares references and returns false. Always compare boxed numbers with equals().

When should you not use the Flyweight pattern?

When there are only a modest number of objects, when little of their state is shared, or when memory is not a measured problem. The pattern splits state across classes and adds a factory, which makes code harder to read for little gain.