Browse Java Design Patterns & Enterprise Application Architecture

Managing Flyweight Factories

Build Java flyweight factories around clear keys, safe caching rules, and lifecycle awareness so sharing remains correct instead of accidental.

On this page

The factory is the operational core of Flyweight. It decides when two requests should receive the same shared instance.

Key Design

The key must include every field that defines intrinsic identity. If the key is too small, unrelated flyweights are merged incorrectly. If it is too large, sharing disappears.

Cache Design

In Java, common choices include:

  • HashMap for scoped single-threaded factories
  • ConcurrentHashMap for shared concurrent lookup
  • bounded caches when flyweight count can grow too far

The factory should also have a clear lifecycle. A process-wide cache and a request-scoped cache have very different behavior.

Review Questions

  • What exactly makes two flyweights identical?
  • How long should shared instances live?
  • What concurrency guarantees are needed?

A weak factory is where most Flyweight bugs come from.

Revised on Thursday, April 23, 2026