Flyweight Design Pattern in Java
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
| Component | Responsibility | In the Basic Example |
|---|---|---|
| Flyweight | Holds intrinsic state; immutable; accepts extrinsic state as method parameters | SeatType |
| Flyweight Factory | Creates each flyweight once and returns the shared instance on later requests | SeatTypeFactory |
| Context | Stores extrinsic state plus a reference to a flyweight | Seat |
| Client | Asks the factory for flyweights and builds contexts | main |
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.
SeatType per category, and thousands of Seat records point to those few shared objects.SeatTypeis the flyweight. It holds only intrinsic state and takes row and number as parameters.SeatTypeFactoryaggregates many flyweights in a map, one per category (hollow diamond, multiplicity*).Seatis the context. The multiplicities (many seats to one type) show the sharing.- The client asks the factory for types and creates the seats itself; it never calls
new SeatType.
5. Step-by-Step Execution Flow
- The client loops over rows and seats and works out each seat's category name.
- It calls
factory.get("VIP"). - On the first call for that name, the factory builds the
SeatType(including its icon) and stores it in the map. - On every later call, the factory returns the instance already in the map.
- The client creates a
Seat(row, number, type): two numbers and one shared reference. - To display a seat,
Seat.describe()callstype.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
Internersprovide 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:
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);
}
}
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.
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
SeatTypehas a private constructor and onlyfinalfields, so only the factory creates it and nobody can change it.SeatTypeFactory.get()usescomputeIfAbsent()to create each type on first request.describe(row, number)receives the extrinsic state instead of storing it.
Expected output
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
- The loop builds 50,000 seats, but the factory creates only three types.
- An identity-based set confirms that only three distinct objects are referenced.
- Each description combines a shared type with that seat's own row and number.
Practical Example: Parallel Catalogue Import
Problem: a nightly job imports 200,000 products on many threads. Every product has a brand, colour and size, and the same values repeat constantly.
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.IntStream;
public class CatalogImportDemo {
// Flyweight: an immutable attribute value
record Attribute(String name, String value) { }
// Thread-safe flyweight pool shared by all import threads
static final class AttributePool {
private final ConcurrentMap<Attribute, Attribute> pool = new ConcurrentHashMap<>();
Attribute of(String name, String value) {
Attribute candidate = new Attribute(name, value);
Attribute existing = pool.putIfAbsent(candidate, candidate); // atomic: first one wins
return existing != null ? existing : candidate;
}
int size() { return pool.size(); }
}
record Product(String sku, List<Attribute> attributes) { }
static final String[] BRANDS = {"Aurel", "Bolt", "Corva", "Dune", "Ember", "Fable", "Grove", "Halo"};
static final String[] COLOURS = {"Black", "White", "Red", "Blue", "Green", "Grey", "Navy", "Olive", "Pink", "Tan", "Teal", "Wine"};
static final String[] SIZES = {"XS", "S", "M", "L", "XL", "XXL"};
public static void main(String[] args) {
AttributePool pool = new AttributePool();
List<Product> products = IntStream.range(0, 200_000)
.parallel() // import rows on many threads
.mapToObj(i -> new Product("SKU-" + i, List.of(
pool.of("brand", BRANDS[i % BRANDS.length]),
pool.of("colour", COLOURS[i % COLOURS.length]),
pool.of("size", SIZES[i % SIZES.length]))))
.toList();
Set<Attribute> distinct = Collections.newSetFromMap(new IdentityHashMap<>());
products.forEach(p -> distinct.addAll(p.attributes()));
long references = products.stream().mapToLong(p -> p.attributes().size()).sum();
System.out.println("Products imported: " + products.size());
System.out.println("Attribute references: " + references);
System.out.println("Attribute objects kept: " + distinct.size() + " (pool size " + pool.size() + ")");
System.out.println("SKU-0 and SKU-12 share the same colour object? "
+ (products.get(0).attributes().get(1) == products.get(12).attributes().get(1)));
}
}
Important classes and methods
Attributeis a record, so it is immutable and itsequals/hashCodeare based on its values, which makes it a good map key.AttributePool.of()usesputIfAbsent()on aConcurrentHashMap. If two threads race, both receive the instance that won.- The losing candidate object is short-lived garbage; only the pooled one stays referenced.
Expected output
Products imported: 200000
Attribute references: 600000
Attribute objects kept: 26 (pool size 26)
SKU-0 and SKU-12 share the same colour object? true
How it runs
- A parallel stream imports products on the common fork-join pool.
- 600,000 attribute references point to only 26 objects: 8 brands, 12 colours and 6 sizes.
- SKU-0 and SKU-12 both have colour "Black" and hold the very same object, so
==istrue.
Real-World Enterprise Example: Shared Compiled Notification Templates
Problem: a notification service sends thousands of messages concurrently from three templates. Parsing a template is the expensive part, and the values change for every recipient.
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.atomic.LongAdder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NotificationTemplateDemo {
// Flyweight: a parsed template, immutable and safe to share between threads
static final class CompiledTemplate {
private static final Pattern PLACEHOLDER = Pattern.compile("\\$\\{(\\w+)}");
private final List<String> literals; // text between placeholders
private final List<String> keys; // placeholder names, in order
private CompiledTemplate(List<String> literals, List<String> keys) {
this.literals = List.copyOf(literals);
this.keys = List.copyOf(keys);
}
static CompiledTemplate compile(String source) { // the expensive step, done once per template
List<String> literals = new ArrayList<>();
List<String> keys = new ArrayList<>();
Matcher m = PLACEHOLDER.matcher(source);
int last = 0;
while (m.find()) {
literals.add(source.substring(last, m.start()));
keys.add(m.group(1));
last = m.end();
}
literals.add(source.substring(last));
return new CompiledTemplate(literals, keys);
}
// Extrinsic state (the values) arrives with each call
String render(Map<String, String> values) {
StringBuilder out = new StringBuilder(literals.get(0));
for (int i = 0; i < keys.size(); i++) {
String value = values.get(keys.get(i));
if (value == null) throw new IllegalArgumentException("Missing value for " + keys.get(i));
out.append(value).append(literals.get(i + 1));
}
return out.toString();
}
}
// Flyweight factory
static final class TemplateRegistry {
private final Map<String, String> sources;
private final Map<String, CompiledTemplate> compiled = new ConcurrentHashMap<>();
private final AtomicInteger compilations = new AtomicInteger();
TemplateRegistry(Map<String, String> sources) { this.sources = Map.copyOf(sources); }
CompiledTemplate get(String id) {
return compiled.computeIfAbsent(id, key -> {
compilations.incrementAndGet();
return CompiledTemplate.compile(sources.get(key));
});
}
int compilations() { return compilations.get(); }
}
public static void main(String[] args) {
TemplateRegistry templates = new TemplateRegistry(Map.of(
"ORDER_SHIPPED", "Hi ${name}, order ${order} has shipped.",
"OTP", "${otp} is your login code, ${name}. Valid for 5 minutes.",
"PAYMENT_FAILED", "Hi ${name}, payment for ${order} failed. Retry in the app."));
String[] ids = {"ORDER_SHIPPED", "OTP", "PAYMENT_FAILED"};
AtomicReferenceArray<String> samples = new AtomicReferenceArray<>(3); // safely shared with the main thread
LongAdder sent = new LongAdder();
try (ExecutorService senders = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 9_000; i++) {
int n = i;
senders.submit(() -> {
String text = templates.get(ids[n % 3]).render(Map.of(
"name", "Customer-" + n,
"order", "ORD-" + (5000 + n),
"otp", String.format(Locale.ROOT, "%06d", (n * 7919) % 1_000_000)));
if (n < 3) samples.set(n, text);
sent.increment();
});
}
} // waits for all tasks
System.out.println("Notifications rendered: " + sent.sum());
System.out.println("Templates compiled: " + templates.compilations());
for (int i = 0; i < samples.length(); i++) {
System.out.println(" " + samples.get(i));
}
}
}
Important classes and methods
CompiledTemplateis the flyweight: parsed text segments and placeholder names, stored in unmodifiable lists.render(values)receives the extrinsic state (name, order, OTP) on every call and stores none of it, so concurrent calls cannot interfere.TemplateRegistryis the factory.computeIfAbsent()guarantees each template is compiled once even when many threads ask at the same time.
Expected output
Notifications rendered: 9000
Templates compiled: 3
Hi Customer-0, order ORD-5000 has shipped.
007919 is your login code, Customer-1. Valid for 5 minutes.
Hi Customer-2, payment for ORD-5002 failed. Retry in the app.
How it runs
- 9,000 tasks run on virtual threads, each picking one of three templates.
- The registry compiles each template on first request: three compilations in total.
- Every task renders with its own values; the first three results are printed as samples.
10. Best Practices and Common Mistakes
Best practices
- Make flyweights deeply immutable:
finalfields, 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
ConcurrentHashMapand 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 twoIntegervalues 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
| Aspect | Flyweight | Singleton | Object Pool | Prototype |
|---|---|---|---|---|
| Goal | Share immutable state among many users | Exactly one instance of a class | Reuse expensive mutable objects | Create new objects by copying |
| Instances | One per distinct value | One | A fixed number | As many as you copy |
| Used concurrently | Yes, by any number of users | Yes | No: borrowed by one user at a time, then returned | Each copy is independent |
| Mutable | Never | Possible | Yes, reset between uses | Copies 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
Integercache 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 insteadQ2. 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.