00:00

Flyweight Design Pattern in Java

Last updated:

The flyweight design pattern in Java saves memory by sharing one immutable object among many users instead of giving each user its own copy. The shared part (the intrinsic state) lives in the flyweight, while the part that differs per use (the extrinsic state) is kept outside and passed in when needed.

It matters when an application holds huge numbers of similar objects: 50,000 stadium seats, 200,000 catalogue products, millions of map markers. If each one carries its own copy of the same category data, memory usage grows with the object count. Flyweight makes it grow with the number of distinct values instead. It is a structural design pattern, and the JDK itself uses the idea in Integer.valueOf() and the string pool.

1. What Is the Flyweight Design Pattern?

The GoF intent is: "Use sharing to support large numbers of fine-grained objects efficiently."

The pattern starts by splitting an object's data in two:

  • Intrinsic state is the same for many objects and does not depend on context: a seat category's name, price, colour and icon.
  • Extrinsic state is unique to each use: the seat's row and number.

The intrinsic state moves into a flyweight object that is created once per distinct value and then shared. A factory hands out these shared instances, creating each one only on first request. The extrinsic state stays in a small context object, or is passed as a method argument when the flyweight needs it.

Because many parts of the program hold the same flyweight, it must be immutable. A change through one reference would otherwise appear everywhere. In object-oriented terms, Flyweight trades a little indirection for a large reduction in duplicated state.

2. Key Components

ComponentResponsibilityIn the Basic Example
FlyweightHolds intrinsic state; immutable; accepts extrinsic state as method parametersSeatType
Flyweight FactoryCreates each flyweight once and returns the shared instance on later requestsSeatTypeFactory
ContextStores extrinsic state plus a reference to a flyweightSeat
ClientAsks the factory for flyweights and builds contextsmain

The client never calls the flyweight's constructor. It asks the factory by key, receives a shared instance, and stores it in a context together with the extrinsic data. When behaviour needs both, the context calls the flyweight and passes its own data in.

3. When Is Flyweight Useful?

  • Seat maps and floor plans: tens of thousands of seats that fall into a handful of categories.
  • Catalogue imports: hundreds of thousands of products whose attributes (brand, colour, size) repeat constantly.
  • Template rendering: a few message templates rendered millions of times with different customer data.

4. UML Class Diagram

The diagram shows the Basic Example.

Flyweight UML class diagram The Client uses SeatTypeFactory and creates Seat records. SeatTypeFactory caches many SeatType flyweights. Many Seat objects share one SeatType each. Client uses SeatTypeFactory - types: Map<String, SeatType> + get(name): SeatType caches * «flyweight» SeatType - name, priceInRupees - colour, icon: byte[] + describe(row, number) «record» Seat row, number, type shares * 1 «create» with extrinsic row and number
Flyweight: the factory caches one SeatType per category, and thousands of Seat records point to those few shared objects.
  1. SeatType is the flyweight. It holds only intrinsic state and takes row and number as parameters.
  2. SeatTypeFactory aggregates many flyweights in a map, one per category (hollow diamond, multiplicity *).
  3. Seat is the context. The multiplicities (many seats to one type) show the sharing.
  4. The client asks the factory for types and creates the seats itself; it never calls new SeatType.

5. Step-by-Step Execution Flow

  1. The client loops over rows and seats and works out each seat's category name.
  2. It calls factory.get("VIP").
  3. On the first call for that name, the factory builds the SeatType (including its icon) and stores it in the map.
  4. On every later call, the factory returns the instance already in the map.
  5. The client creates a Seat(row, number, type): two numbers and one shared reference.
  6. To display a seat, Seat.describe() calls type.describe(row, number), combining shared and per-seat data at that moment.

6. Real-World Use Cases

  • E-commerce: deduplicated product attributes, category metadata and price-band objects in large catalogues.
  • Payments and banking: shared currency, card-scheme and merchant-category objects referenced by millions of transactions in a batch.
  • Notifications: compiled message templates rendered with per-recipient data.
  • The JDK: Integer.valueOf() returns cached objects for values from -128 to 127, Boolean.valueOf() always returns one of two constants, and string literals are shared through the string pool (String.intern()). Enum constants are also shared single instances.
  • Libraries: Guava's Interners provide ready-made strong and weak flyweight pools.

7. Problem Without the Pattern

A seat map where every seat carries its own copy of its category:

SeatMapWithoutFlyweight.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;

public class SeatMapWithoutFlyweight {

    static long iconBytes = 0;

    // Category data, duplicated inside every seat
    static final class SeatType {
        final String name;
        final int priceInRupees;
        final String colour;
        final byte[] icon;

        SeatType(String name, int priceInRupees, String colour) {
            this.name = name;
            this.priceInRupees = priceInRupees;
            this.colour = colour;
            this.icon = new byte[1024];                        // a small rendered icon
            iconBytes += icon.length;
        }
    }

    record Seat(int row, int number, SeatType type) { }

    static SeatType newTypeFor(int row) {
        if (row <= 10) return new SeatType("VIP", 4500, "gold");
        if (row <= 60) return new SeatType("PREMIUM", 2500, "blue");
        return new SeatType("GENERAL", 800, "grey");
    }

    public static void main(String[] args) {
        List<Seat> seats = new ArrayList<>();
        for (int row = 1; row <= 250; row++) {
            for (int number = 1; number <= 200; number++) {
                seats.add(new Seat(row, number, newTypeFor(row)));   // a new SeatType per seat
            }
        }
        Set<SeatType> distinct = Collections.newSetFromMap(new IdentityHashMap<>());
        seats.forEach(seat -> distinct.add(seat.type()));

        System.out.println("Seats:            " + seats.size());
        System.out.println("SeatType objects: " + distinct.size());
        System.out.println("Icon bytes:       " + iconBytes);
    }
}
Console
Seats:            50000
SeatType objects: 50000
Icon bytes:       51200000
  • Memory waste: 50,000 category objects and about 51 MB of icons for three real categories.
  • Garbage-collection pressure: more live objects mean longer and more frequent collections.
  • Maintainability: changing the VIP price means updating 2,000 objects, and missing one leaves inconsistent data.

8. Solution Using the Pattern

Move name, price, colour and icon into an immutable SeatType, create it through a factory keyed by category name, and let each seat keep only its row, number and a reference.

Memory now depends on the number of categories, not seats: three objects and about 3 KB of icons. A price change is one new SeatType in one place. The seat class shrinks to its genuinely unique data, which is easier to read and serialise.

9. Flyweight Design Pattern in Java: Code Examples

Each example is a single file that runs on Java 21 with java FileName.java.

Basic Example: Stadium Seat Map

Problem: fix section 7 so that 50,000 seats share three category objects.

StadiumSeatMapDemo.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class StadiumSeatMapDemo {

    static long iconBytes = 0;

    // Flyweight: intrinsic state only, immutable and shared
    static final class SeatType {
        private final String name;
        private final int priceInRupees;
        private final String colour;
        private final byte[] icon;

        private SeatType(String name, int priceInRupees, String colour) {
            this.name = name;
            this.priceInRupees = priceInRupees;
            this.colour = colour;
            this.icon = new byte[1024];
            iconBytes += icon.length;
        }

        // Extrinsic state (row, number) is passed in, never stored
        String describe(int row, int number) {
            return "Row " + row + " Seat " + number + ": " + name + ", Rs. " + priceInRupees + ", " + colour;
        }
    }

    // Flyweight factory: creates each SeatType once and hands out the shared instance
    static final class SeatTypeFactory {
        private final Map<String, SeatType> types = new HashMap<>();

        SeatType get(String name) {
            return types.computeIfAbsent(name, key -> switch (key) {
                case "VIP" -> new SeatType("VIP", 4500, "gold");
                case "PREMIUM" -> new SeatType("PREMIUM", 2500, "blue");
                case "GENERAL" -> new SeatType("GENERAL", 800, "grey");
                default -> throw new IllegalArgumentException("Unknown seat type " + key);
            });
        }
    }

    // Context: the extrinsic state plus a reference to the shared flyweight
    record Seat(int row, int number, SeatType type) {
        String describe() { return type.describe(row, number); }
    }

    public static void main(String[] args) {
        SeatTypeFactory factory = new SeatTypeFactory();
        List<Seat> seats = new ArrayList<>();
        for (int row = 1; row <= 250; row++) {
            String typeName = row <= 10 ? "VIP" : row <= 60 ? "PREMIUM" : "GENERAL";
            for (int number = 1; number <= 200; number++) {
                seats.add(new Seat(row, number, factory.get(typeName)));
            }
        }
        Set<SeatType> distinct = Collections.newSetFromMap(new IdentityHashMap<>());
        seats.forEach(seat -> distinct.add(seat.type()));

        System.out.println("Seats:            " + seats.size());
        System.out.println("SeatType objects: " + distinct.size());
        System.out.println("Icon bytes:       " + iconBytes);
        System.out.println(seats.get(6).describe());
        System.out.println(seats.get(49_999).describe());
    }
}

Important classes and methods

  • SeatType has a private constructor and only final fields, so only the factory creates it and nobody can change it.
  • SeatTypeFactory.get() uses computeIfAbsent() to create each type on first request.
  • describe(row, number) receives the extrinsic state instead of storing it.

Expected output

Console
Seats:            50000
SeatType objects: 3
Icon bytes:       3072
Row 1 Seat 7: VIP, Rs. 4500, gold
Row 250 Seat 200: GENERAL, Rs. 800, grey

How it runs

  1. The loop builds 50,000 seats, but the factory creates only three types.
  2. An identity-based set confirms that only three distinct objects are referenced.
  3. Each description combines a shared type with that seat's own row and number.

10. Best Practices and Common Mistakes

Best practices

  • Make flyweights deeply immutable: final fields, no setters, unmodifiable collections.
  • Hide constructors and create flyweights only through the factory.
  • Pass extrinsic state as method parameters rather than storing it on the flyweight.
  • Thread safety: immutable flyweights are safe to share across threads. Make the factory itself thread-safe with ConcurrentHashMap and atomic operations.

Common mistakes

  • Mutable flyweights, where one caller's change leaks to every other user.
  • Unbounded pools keyed by user input, which become memory leaks.
  • Comparing with == outside the pool, such as two Integer values above 127.
  • Overengineering: applying Flyweight to a few hundred objects, where the savings are negligible.

11. When to Use and When Not to Use

Use it when profiling shows many duplicate objects, when most state can be made extrinsic, and when the number of distinct intrinsic values is small and stable.

Avoid it when objects are few, when most data is unique per object, or when computing and passing extrinsic state costs more than the memory you save. Measure first, with a heap histogram, before reshaping a model for memory.

12. Advantages and Disadvantages

Advantages

  • Large memory savings for many similar objects.
  • Less garbage-collection work because fewer objects stay live.
  • One source of truth for shared data.
  • Thread-safe sharing once flyweights are immutable.

Disadvantages

  • More complex design: state is split across objects.
  • Runtime cost of factory lookups and passing extrinsic data.
  • Pool management: growth limits and eviction must be considered.

13. Comparison with Similar Patterns

AspectFlyweightSingletonObject PoolPrototype
GoalShare immutable state among many usersExactly one instance of a classReuse expensive mutable objectsCreate new objects by copying
InstancesOne per distinct valueOneA fixed numberAs many as you copy
Used concurrentlyYes, by any number of usersYesNo: borrowed by one user at a time, then returnedEach copy is independent
MutableNeverPossibleYes, reset between usesCopies usually are

Choose Flyweight to cut duplication of identical, read-only data. Choose a Singleton for one global service, an Object Pool (such as a database connection pool) for scarce resources that one caller uses at a time, and Prototype when each user needs its own modifiable copy. A factory is the usual way to hand out flyweights.

14. Summary

  • The flyweight design pattern in Java shares immutable objects to support huge numbers of similar items.
  • Purpose: reduce memory use by storing each distinct value once.
  • Components: Flyweight (intrinsic state), Flyweight Factory, Context (extrinsic state), Client.
  • The factory returns cached instances; contexts pass their own data into flyweight methods.
  • Used in seat maps, catalogues, templates, and in the JDK's Integer cache and string pool.
  • Benefits: less memory, less GC pressure, one source of truth.
  • Keep flyweights immutable, the factory thread-safe and the pool bounded, and measure before applying it.

15. Java Design Pattern Interview Questions and Answers

Q1. Why does Integer.valueOf(127) == Integer.valueOf(127) return true but the same check with 128 return false?

Integer.valueOf() is a flyweight factory: it returns cached objects for -128 to 127, and autoboxing calls it. Values outside that range get new objects, so == compares two different references. The upper bound can be raised with -XX:AutoBoxCacheMax, but the fix is to compare wrapper values with equals().

Integer a = 127, b = 127;   // true:  same cached object
Integer c = 128, d = 128;   // false: two separate objects (default cache)
System.out.println(a == b);
System.out.println(c == d);
System.out.println(c.equals(d));   // true: compare values instead
Q2. How do String.intern() and G1 string deduplication relate to Flyweight?

Both share identical string data. intern() returns the canonical instance from the string pool, which is on the heap since Java 7, so equal interned strings are ==. G1's -XX:+UseStringDeduplication (Java 8u20 and later; other collectors since Java 18) shares the backing byte arrays of equal strings in the background without changing object identity.

Q3. A developer adds setPrice() to SeatType to give one seat a discount. What happens?

Every seat sharing that flyweight gets the new price, because they all point to the same object. Per-seat differences are extrinsic state: store the discount on the seat (context) or pass it as a parameter, and keep the flyweight immutable. If a category really changes, create a new flyweight and switch the references deliberately.

Q4. The flyweight pool is keyed by values from user input and keeps growing. How do you fix it?

An unbounded pool is a memory leak. Bound it with a size-limited cache such as Caffeine, or use a weak interner, for example Guava's Interners.newWeakInterner(), so entries disappear when nothing else references them. Better still, validate keys so only a known, finite set of values can enter the pool.

Q5. How would you prove that Flyweight actually reduced memory in a service?

Compare heap usage before and after under the same load. jcmd <pid> GC.class_histogram shows instance counts and bytes per class, Java Flight Recorder records allocation profiles, and a heap dump analysed in a tool such as Eclipse MAT shows duplicate objects and retained sizes. For single objects, JOL (Java Object Layout) reports exact sizes.