ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. Specialized Collections
Book 1 · Volume II — Generics, Collections & Type System · Topic 7.3

Specialized Collections

Enum collections and weak-reference collections

13 min readStage 1 · Foundations15 interview questions
Prerequisites
4.3 Set Implementations · 4.4 Map Implementations
Covers
Enum collections · Weak-reference collections
Related
Book 2 (reference types, garbage collection) · Book 7 (caching)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

Specialised collections exploit knowledge about their keys or elements. Enum collections — EnumSet and EnumMap — know the complete, fixed set of possible keys and use bit vectors and ordinal-indexed arrays. Weak-reference collections — chiefly WeakHashMap — hold keys through weak references so that entries vanish when the keys are no longer used elsewhere.

2Why It Exists

Before Java 5, sets of options were usually int constants combined as bit masks: READ | WRITE. Masks are fast and small but not type-safe: any int is accepted, printing one shows a number, and adding a 33rd flag means changing every signature from int to long. Enums fixed the type safety, and EnumSet and EnumMap, added with them, keep the speed: because the set of possible keys is fixed and numbered by ordinal(), membership can be a bit and a map can be an array. The general collections cannot use that knowledge, so HashSet<Feature> and HashMap<Feature, V> pay for hashing and entry objects they do not need.

Weak-reference collections solve a different problem: attaching data to objects whose lifetime other code controls. If a framework keeps per-session or per-class-loader metadata in an ordinary map, the map keeps every key alive and the metadata outlives its object, which is a memory leak. WeakHashMap, available since Java 1.2 with the java.lang.ref package, lets the garbage collector decide: when nothing else uses the key, the entry goes.

3Core Concepts

Enum collections

EnumSet stores membership as bits (4.3); EnumMap stores values in an array indexed by ordinal() (4.4). Both are faster and far smaller than hash-based equivalents, iterate in declaration order, reject null keys and are not thread-safe. They are the idiomatic way to model flags, permissions, states, and per-type configuration or handlers — replacing both int bit masks and HashMap<Enum, V>.

How EnumSet and EnumMap represent their contents
Figure 1 — How EnumSet and EnumMap represent their contents

Weak-reference collections

Java has four reference strengths. A weak reference does not keep its target alive: once an object is reachable only through weak references, the GC clears them. WeakHashMap uses weak references for keys, so an entry is removed after its key becomes unreachable elsewhere — useful for attaching metadata to objects whose lifecycle is controlled by other code, such as class loaders, sessions, or UI components. Values are strong, so values must not reference their keys.

Reference strengths, from strongest to weakest
Figure 2 — Reference strengths, from strongest to weakest

Weak collections are not caches: eviction depends on GC timing, not on size, age or usefulness. Soft references, cleared under memory pressure, were once used for caches but make memory behaviour unpredictable. Production caches should use explicit policies (Caffeine offers weak or soft keys and values as options alongside size and time limits).

4How It Works Internally

EnumSet is abstract; its factories pick an implementation from the size of the enum. For up to 64 constants, RegularEnumSet stores the whole set in one long: contains(e) is (bits & (1L << e.ordinal())) != 0, and addAll, retainAll and complementOf are single bitwise operations. Larger enums get a JumboEnumSet with a long[]. Both share the enum's array of constants, so iteration walks the set bits in ordinal order, which is declaration order. EnumMap keeps an Object[] of values indexed by ordinal, with a private marker standing in for null values; keys cannot be null because null has no ordinal.

WeakHashMap is a hash table whose entries extend WeakReference: the entry refers to its key weakly and to its value strongly, and is registered with a ReferenceQueue owned by the map. When the key becomes unreachable except through such references, the collector clears the reference and puts the entry on the queue. The map does no work in the background: on its next get, put, size or similar call, expungeStaleEntries() drains the queue and unlinks those entries and their values (Figure 3). A null key is replaced by a static marker object, which is always reachable, so a null-key entry is never removed.

A WeakHashMap entry is removed only after the GC clears its key and the map is next used
Figure 3 — A WeakHashMap entry is removed only after the GC clears its key and the map is next used

5APIs / Features / Syntax

The factory and utility methods of the enum collections, and the weak-reference types:

APIPurpose
EnumSet.noneOf / allOf(Class), of(e, ...)Empty, full, or listed set of one enum type
EnumSet.range(from, to), complementOf(set), copyOf(collection)Ranges by declaration order, the missing constants, a copy
new EnumMap<>(Feature.class), new EnumMap<>(map)Ordinal-indexed map; key type given explicitly or taken from a non-empty map
WeakHashMapKeys held weakly, values strongly; not thread-safe
WeakReference, SoftReference, PhantomReference, ReferenceQueueThe java.lang.ref types the weak collections are built on
java.lang.ref.Cleaner (Java 9)Run clean-up code after an object becomes unreachable
ClassValue (Java 7)Lazily computed value per Class, without keeping class loaders alive

Neither enum collection is thread-safe; wrap it with Collections.synchronizedSet or synchronizedMap, or publish an unmodifiable copy (7.1). EnumSet has no public constructor and no immutable variant of its own: Collections.unmodifiableSet(EnumSet.of(...)) keeps the bit-vector speed, and Set.copyOf gives an immutable but hash-based set.

6Practical Examples

Example 1 — Enum and weak-reference collections

Problem. A product models features per subscription plan, timeouts per feature, and the time each worker thread was last seen, without keeping finished threads alive.

JAVAEnum and weak-reference collections
enum Feature { SEARCH, EXPORT, API_ACCESS, SSO, AUDIT }

// Plans as EnumSets
EnumSet<Feature> basic = EnumSet.of(Feature.SEARCH, Feature.EXPORT);
EnumSet<Feature> enterprise = EnumSet.allOf(Feature.class);
boolean hasSso = basic.contains(Feature.SSO);                  // false

// Per-feature configuration
EnumMap<Feature, Duration> timeouts = new EnumMap<>(Feature.class);
timeouts.put(Feature.EXPORT, Duration.ofMinutes(5));

// Metadata tied to key lifetime
Map<Thread, Instant> lastSeen = Collections.synchronizedMap(new WeakHashMap<>());
lastSeen.put(Thread.currentThread(), Instant.now());
// When a thread object is no longer referenced anywhere else, its entry goes away.

Why it works. The plans are bit vectors, so contains is a single bit test. EnumMap needs the key class in its constructor because it sizes its array from the enum's constants. The WeakHashMap refers to each Thread weakly, and the synchronizedMap wrapper is needed because several threads write to it; once a finished thread is no longer referenced anywhere else, its entry is removed on a later map operation.

Example 2 — Mini program: subscription plans with EnumSet and EnumMap

Problem. A SaaS product has three plans. It must list what each plan includes, find what a plan lacks, grant only the requested features a plan allows, store a plan's features compactly, and keep per-feature limits.

JAVAFeaturePlans.java
public class FeaturePlans {
    enum Feature { SEARCH, EXPORT, API_ACCESS, SSO, AUDIT }
    enum Plan { FREE, TEAM, ENTERPRISE }
 
    static final Map<Plan, Set<Feature>> FEATURES = new EnumMap<>(Map.of(
            Plan.FREE, EnumSet.of(Feature.SEARCH),
            Plan.TEAM, EnumSet.range(Feature.SEARCH, Feature.API_ACCESS),
            Plan.ENTERPRISE, EnumSet.allOf(Feature.class)));
 
    static long toMask(Set<Feature> fs) {           // e.g. for a token claim
        long m = 0;
        for (Feature f : fs) m |= 1L << f.ordinal();
        return m;
    }
    static EnumSet<Feature> fromMask(long m) {
        EnumSet<Feature> fs = EnumSet.noneOf(Feature.class);
        for (Feature f : Feature.values())
            if ((m & (1L << f.ordinal())) != 0) fs.add(f);
        return fs;
    }
 
    public static void main(String[] args) {
        FEATURES.forEach((p, fs) -> System.out.println(p + ": " + fs));
        Set<Feature> missing = EnumSet.complementOf(
                EnumSet.copyOf(FEATURES.get(Plan.TEAM)));
        System.out.println("TEAM lacks: " + missing);
 
        EnumSet<Feature> requested = EnumSet.of(Feature.SSO, Feature.EXPORT);
        requested.retainAll(FEATURES.get(Plan.TEAM));      // set intersection
        System.out.println("TEAM grants of [SSO, EXPORT]: " + requested);
 
        long mask = toMask(FEATURES.get(Plan.TEAM));
        System.out.println("TEAM mask: " + Long.toBinaryString(mask)
                + " -> " + fromMask(mask));
 
        Map<Feature, Integer> dailyLimit = new EnumMap<>(Feature.class);
        dailyLimit.put(Feature.EXPORT, 50);
        dailyLimit.put(Feature.SEARCH, 10_000);   // keys kept in ordinal order
        System.out.println("limits: " + dailyLimit);
    }
}
OUTPUT
FREE: [SEARCH]
TEAM: [SEARCH, EXPORT, API_ACCESS]
ENTERPRISE: [SEARCH, EXPORT, API_ACCESS, SSO, AUDIT]
TEAM lacks: [SSO, AUDIT]
TEAM grants of [SSO, EXPORT]: [EXPORT]
TEAM mask: 111 -> [SEARCH, EXPORT, API_ACCESS]
limits: {SEARCH=10000, EXPORT=50}

Why it behaves this way. EnumSet.range takes every constant from SEARCH to API_ACCESS in declaration order, and complementOf flips the bits, so the team plan lacks exactly SSO and AUDIT. retainAll is a bitwise AND. The mask shows the same bits the RegularEnumSet keeps internally, useful for compact storage, although names are safer in a database (section 9). Both maps print in ordinal order whatever the insertion order, because EnumMap iterates its array: the Map.of used to build FEATURES has a random order, and the EnumMap copy does not.

Example 3 — Weak keys, and the value that keeps its key alive

Problem. A web framework keeps metadata per Session object in a WeakHashMap, so that metadata disappears with the session. One team's metadata record also holds a reference to its session. The program asks the garbage collector to run and checks which entries go.

JAVAWeakMetadata.java
public class WeakMetadata {
    static final class Session {
        final String id;
        Session(String id) { this.id = id; }
    }
    record Info(String user) {}
    record LeakyInfo(String user, Session session) {}   // value -> key
 
    static boolean collected(Map<?, ?> m, int expected)
            throws InterruptedException {
        for (int i = 0; i < 50 && m.size() > expected; i++) {
            System.gc();
            Thread.sleep(100);                          // let the GC clear refs
        }
        return m.size() == expected;
    }
 
    public static void main(String[] args) throws InterruptedException {
        Map<Session, Info> meta = new WeakHashMap<>();
        Session kept = new Session("s1");
        meta.put(kept, new Info("ann"));
        meta.put(new Session("s2"), new Info("raj"));  // no other reference
        System.out.println("before GC: " + meta.size() + " entries");
        System.out.println("after GC, s2 gone: " + collected(meta, 1)
                + ", s1 still there: " + meta.containsKey(kept));
 
        Map<Session, LeakyInfo> leaky = new WeakHashMap<>();
        Session s3 = new Session("s3");
        leaky.put(s3, new LeakyInfo("li", s3));
        s3 = null;                              // only the map refers to it
        System.out.println("value refers to key, entry collected: "
                + collected(leaky, 0));
    }
}
OUTPUT
before GC: 2 entries
after GC, s2 gone: true, s1 still there: true
value refers to key, entry collected: false

Why it behaves this way. s2 had no reference outside the map, so the collector cleared its weak reference and the map removed the entry when size() was called; s1 is still referenced by kept. The leaky entry's value refers to its own key, and the map holds values strongly, so the key remains reachable through the map and is never collected (Figure 3). System.gc() is only a request, which is why the program retries; production code must never depend on when a weak entry disappears.

Example 4 — Allowed state transitions as an EnumMap of EnumSets

Problem. An order moves through five states, and only some transitions are legal. The rules should be data that can be read and tested, not a chain of if statements, and counting orders per state should be cheap.

JAVAOrderStates.java
public class OrderStates {
    enum State { NEW, PAID, SHIPPED, DELIVERED, CANCELLED }
 
    static final Map<State, Set<State>> NEXT = new EnumMap<>(State.class);
    static {
        NEXT.put(State.NEW, EnumSet.of(State.PAID, State.CANCELLED));
        NEXT.put(State.PAID, EnumSet.of(State.SHIPPED, State.CANCELLED));
        NEXT.put(State.SHIPPED, EnumSet.of(State.DELIVERED));
        for (State s : State.values())                    // terminal states
            NEXT.putIfAbsent(s, EnumSet.noneOf(State.class));
    }
 
    static State move(State from, State to) {
        if (!NEXT.get(from).contains(to))
            throw new IllegalStateException(from + " -> " + to
                    + ": not allowed");
        return to;
    }
 
    public static void main(String[] args) {
        State s = State.NEW;
        for (State to : List.of(State.PAID, State.SHIPPED, State.DELIVERED))
            s = move(s, to);
        System.out.println("reached " + s);
        try {
            move(State.SHIPPED, State.CANCELLED);
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage());
        }
        Map<State, Integer> counts = new EnumMap<>(State.class);
        var orders = List.of(State.PAID, State.NEW, State.PAID,
                State.DELIVERED);
        for (State x : orders)
            counts.merge(x, 1, Integer::sum);
        System.out.println("orders per state: " + counts);
    }
}
OUTPUT
reached DELIVERED
SHIPPED -> CANCELLED: not allowed
orders per state: {NEW=1, PAID=2, DELIVERED=1}

Why it behaves this way. NEXT maps each state to the set of states it may move to; the loop fills in empty sets for the terminal states, so every lookup succeeds. A legal path reaches DELIVERED, and cancelling a shipped order is rejected with a clear message. The counts map prints in state order, not in the order orders arrived, and merge adds to a slot of an array instead of hashing.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
HashSet<Enum> or HashMap<Enum, V> where EnumSet / EnumMap fitMore memory, hashing on every call, and iteration in no useful orderEnumSet.of / noneOf and new EnumMap<>(Type.class)
Persisting ordinal() or a bit mask in a databaseReordering or inserting a constant silently changes the meaning of stored dataStore the constant names; convert masks only at the edge
A WeakHashMap value that refers to its keyThe key stays reachable through the map: entries are never removed (Example 3)Keep values free of key references, or wrap them in a WeakReference
Using WeakHashMap as a cacheEntries vanish at the next GC or never; hit rate is unpredictableA cache with size and expiry limits (Caffeine)
WeakHashMap with String literals, small Integers or enum constants as keysThose keys are always reachable, so entries are never removedUse keys whose lifetime the map is meant to follow
Sharing an EnumSet, EnumMap or WeakHashMap between threads unsynchronisedLost updates and corrupted state: none of them is thread-safeSynchronised wrappers, confinement, or immutable copies

8Performance & Production Considerations

An EnumSet of up to 64 constants is one object holding a long: a few dozen bytes, compared with a HashSet that needs a table and a node per element. Its bulk operations are single machine instructions, which makes it suitable for permission checks on every request. EnumMap gets and puts are array accesses with no hashCode or equals calls. These differences rarely dominate a service, but they are free to take.

WeakHashMap behaviour depends on the garbage collector, which makes it hard to test and to reason about under load: entries can disappear immediately after a collection, or survive for hours if the keys are reachable through some forgotten reference. Stale entries are removed only when the map is used, so an idle map keeps its values. Monitor such maps' sizes in production, never use them for data that must be found again, and prefer explicit lifecycles, such as removing metadata when a session ends, wherever the owning code can do so.

9Architecture & Design Considerations

Enums with EnumSet and EnumMap are a compact way to put domain rules into data: plans and their features, roles and permissions, states and their transitions (Example 4). Keep the persisted and transmitted form independent of declaration order, by using constant names or explicit codes, so that constants can be added or reordered without a data migration.

Match the collection to what the keys are and how long entries must live
Figure 4 — Match the collection to what the keys are and how long entries must live

Weak references are a tool for libraries and frameworks that attach data to objects they do not own, such as sessions, threads, class loaders or UI components. Application code rarely needs them; when it does, the usual alternatives are an explicit lifecycle hook, ClassValue for per-class data, or a proper cache with size and time limits (Figure 4).

10Interview Questions & Answers

Q1L1 · BasicConcept

Why use EnumSet instead of HashSet for enum values?

EnumSet stores membership as bits, making operations single bitwise instructions, using a few bytes of memory, and iterating in declaration order.

Q2L2 · IntermediateInternals

How does EnumMap store its entries?

In an array indexed by the key's ordinal, with no hashing and no per-entry node objects.

Q3L3 · Senior EngineerInternals

When is an entry removed from a WeakHashMap?

After its key becomes only weakly reachable and the GC clears the weak reference; the map then purges the entry on its next operation.

Q4L3 · Senior EngineerTrade-off

Why is WeakHashMap a poor general-purpose cache?

Eviction is driven by GC reachability of keys, not by size, age or access patterns: entries may disappear immediately or never (for example when values reference keys or keys are long-lived constants). Caches need explicit bounds and expiry, as provided by libraries like Caffeine.

Q5L1 · BasicConcept

Can an EnumMap have a null key or null values?

Keys cannot be null: an EnumMap locates a key by its ordinal(), and null has none, so put(null, v) throws NullPointerException. Values may be null; the map stores a private marker in its array so that a null value can be told apart from a missing one. EnumSet likewise rejects null elements.

Q6L2 · IntermediateCode

What does this program print?

JAVAEnumSetQuiz.java
public class EnumSetQuiz {
    enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
 
    public static void main(String[] args) {
        Set<Day> s = EnumSet.of(Day.SUN, Day.WED, Day.MON);
        Set<Day> work = EnumSet.range(Day.MON, Day.FRI);
        System.out.println(s + " " + EnumSet.complementOf(EnumSet.copyOf(work))
                + " " + s.containsAll(work));
    }
}

It prints [MON, WED, SUN] [SAT, SUN] false. An EnumSet always iterates in declaration order, whatever the order of the arguments, so SUN, WED, MON prints as MON, WED, SUN. range(MON, FRI) is the five working days and its complement is the weekend. s does not contain every working day, so containsAll is false.

Q7L2 · IntermediateConcept

What are the four reference strengths in Java, and which one does WeakHashMap use?

Strong references, the normal kind, keep an object alive. A soft reference is cleared only when memory runs short, a weak reference at the next collection once the object is otherwise unreachable, and a phantom reference never gives the object back and only signals, through a queue, that it has been collected. WeakHashMap holds its keys through weak references and its values strongly.

Q8L3 · Senior EngineerCode

What does this program print?

JAVAWeakLiteralQuiz.java
public class WeakLiteralQuiz {
    public static void main(String[] args) throws InterruptedException {
        Map<String, Integer> limits = new WeakHashMap<>();
        limits.put("export", 50);
        for (int i = 0; i < 5; i++) { System.gc(); Thread.sleep(50); }
        System.out.println(limits);
    }
}

It prints {export=50}, however often the collector runs. The key is a string literal, which is interned and referenced from the class's constant pool, so it stays strongly reachable as long as the class is loaded and the weak reference is never cleared. Cached Integer values, enum constants and other shared constants behave the same way, which is why they make useless weak keys.

Q9L3 · Senior EngineerInternals

What is the difference between RegularEnumSet and JumboEnumSet?

Both are private implementations chosen by the EnumSet factories. An enum with up to 64 constants gets a RegularEnumSet, which keeps the whole set in one long with one bit per ordinal. Larger enums get a JumboEnumSet with a long[], one word per 64 constants, plus a cached size. The API and the behaviour are the same; only the representation and a little speed differ, which is why code should declare EnumSet or Set, never the implementation.

Q10L3 · Senior EngineerTricky

A team stores each customer's enabled features as an ordinal bit mask in a database column. What can go wrong, and what would you do instead?

The meaning of every stored mask depends on the declaration order of the enum. Inserting a constant in the middle, reordering them, or removing one silently changes which features existing customers have, with no error anywhere. Store the feature names, for example as a set of strings or a join table, and convert to EnumSet when loading; if a compact form is required, assign each constant an explicit, fixed code and never reuse one.

Q11L3 · Senior EngineerScenario

A long-running service leaks memory. A heap dump shows a WeakHashMap<Session, SessionStats> with millions of entries, although sessions end after minutes. Diagnose and fix.

Weak keys are removed only when the key becomes unreachable, so something still reaches the sessions. The usual cause is the value: if SessionStats holds a reference to its Session, directly or through a listener or a lambda, the map's strong reference to the value keeps the key alive (Example 3). Remove that reference, or store only the data needed, and better still remove the stats explicitly from the session-end hook. Then verify with a second heap dump that entries are released.

Q12L4 · Technical ArchitectDesign

Design feature entitlements for a multi-tenant product with three plans and per-tenant add-ons.

Model features as an enum and each plan as an EnumSet, kept in an EnumMap<Plan, Set<Feature>> built once at start-up, as in Example 2. A tenant's entitlements are its plan's set plus its add-ons, computed as a new EnumSet and cached per tenant as an unmodifiable set. Persist plans and add-ons by feature name, so the enum can evolve, and check entitlements in one service method that every endpoint calls. Feature limits fit an EnumMap<Feature, Integer> per plan.

Q13L4 · Technical ArchitectTrade-off

For behaviour that varies by enum constant, do you use an EnumMap of handlers, a switch, or abstract methods on the enum?

An exhaustive switch expression over the enum is the most readable for a single, small decision, and the compiler reports missing cases. Abstract methods on the enum keep behaviour with the constant, but put logic into the enum that may belong elsewhere. An EnumMap<Type, Handler> keeps the behaviour outside the enum and can be configured or replaced at run time, at the cost of a lookup that can find no handler. Choose a switch for simple mappings, enum methods for intrinsic behaviour and an EnumMap for pluggable handlers.

Q14L5 · Solution ArchitectDesign

A team proposes WeakHashMap as the product catalogue cache "so memory is freed automatically". What do you recommend instead?

A weak map frees entries when the keys become unreachable, which says nothing about how often or how recently the catalogue entries are used, so the hit rate would depend on GC timing. Use a real cache: Caffeine in-process with a maximum size, an expiry time and metrics, and, if several instances need the same data or the data is large, a shared cache such as Redis. Decide the invalidation strategy (expiry, events on change) explicitly, because that, not memory, is the hard part of caching.

Q15L5 · Solution ArchitectTrade-off

A plugin platform attaches metadata to classes loaded by plugin class loaders. Compare WeakHashMap<Class<?>, Meta>, ClassValue and explicit unregistration.

A WeakHashMap keyed by Class frees entries after a plugin's loader is collected, but any value that refers to the class, its loader or a lambda from the plugin pins the whole loader, a classic metaspace leak. ClassValue was designed for this: the JVM ties the value to the class without making the class reachable from a global map. Explicit unregistration in the plugin's stop hook is the most predictable and testable, but relies on every plugin being stopped properly. Platforms usually combine explicit clean-up with ClassValue as the safety net, and test unloading with heap dumps.

Test your knowledge on this topic →Flashcards from this topic's 15 questions, filtered by level and type.

Key Takeaways

  • EnumSet (bits) and EnumMap (ordinal array) are the default for enum keys.
  • WeakHashMap entries live only as long as their keys are strongly reachable elsewhere.
  • Weak collections are for key-lifetime metadata, not caching.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.