Quick revision
The short answer
SESSIONS is a static field, so the map is reachable from a GC root for as long as SessionRegistry's class is loaded, which for application code is forever. Every Session ever registered stays reachable through it, along with everything each Session references, so the heap grows with every login until OutOfMemoryError; on top of that, a plain HashMap is not safe for concurrent registration. The fix is to remove entries on logout and on expiry, or to replace the map with a bounded, expiring cache such as Caffeine with expireAfterAccess and maximumSize; weak keys do not help here, because a String id's lifetime does not define the session's lifetime.
What to remember
In this answer, we saw that a static map is reachable from a GC root for as long as its class is loaded, so every registered Session and everything it references stays alive, and the heap grows until OutOfMemoryError. The heap dump shows one dominator reached through the static field. HashMap is also unsafe for concurrent registration. We fixed it by removing sessions on logout and expiry, or with a Caffeine cache using expireAfterAccess and maximumSize, and saw why weak keys do not help when a String id does not define the session's lifetime.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
SESSIONS is a static field, so the map is reachable from a GC root for as long as SessionRegistry's class is loaded, which for application code is forever. Every Session ever registered stays reachable through it, along with everything each Session references, so the heap grows with every login until OutOfMemoryError; on top of that, a plain HashMap is not safe for concurrent registration. The fix is to remove entries on logout and on expiry, or to replace the map with a bounded, expiring cache such as Caffeine with expireAfterAccess and maximumSize; weak keys do not help here, because a String id's lifetime does not define the session's lifetime.
Why this question is asked
This is the most common shape of a Java memory leak: a long-lived collection that only ever grows. It usually works fine in testing, where there are a few hundred logins, and fails in production after days or weeks. Interviewers ask it to see whether we can explain a leak in terms of reachability and then fix it properly, including the concurrency bug hiding in the same code. In this answer, we will see why the sessions are never collected, reproduce the growth, find it in a heap dump, fix the concurrency problem, and then fix the leak with explicit removal and with a bounded cache, before looking at why weak keys are the wrong tool.
1Why the Sessions Are Never Collected
The garbage collector frees an object only when it cannot be reached from any GC root. Static fields are roots for as long as their class is loaded, and SessionRegistry is loaded by the application class loader, which is never unloaded while the service runs. So the path from the root to every Session is permanent: the static field points to the HashMap, the map's table points to its nodes, and each node points to a Session.
Notice that each Session also keeps everything it references alive: user profiles, shopping carts, cached permissions, perhaps a few large byte arrays. The leak is not just the size of the map entries; it is the retained size of every session object graph.
- GC root: class SessionRegistryLoaded by the application class loader, never unloaded
- static field SESSIONSAlways reachable
- HashMap and its tableGrows with every login
- HashMap.Node entriesOne per registered session
- Session objectsPlus users, carts, buffers they reference
5 layers, from the top down. Step through them one at a time.
2Seeing the Leak in the Heap and in a Dump
In GC logs, the heap after each full or mixed collection keeps rising, because the live set grows with every login. To find the cause, we take a heap dump, ideally automatically with -XX:+HeapDumpOnOutOfMemoryError, or on demand with jcmd.
Notice that one object, the HashMap held by a static field, retains over 90 percent of the heap. A single dominator with a huge retained size, reached through a static field, is the classic fingerprint of this kind of leak.
3The Concurrency Bug in the Same Code
The register method is called on every login, which happens on many request threads at the same time. HashMap is not thread-safe: concurrent puts can lose entries, corrupt the internal structure during a resize, and leave other threads reading inconsistent data. So even before the leak matters, the code is wrong. Using ConcurrentHashMap fixes the concurrency part, but not the leak, because a concurrent map that only grows is still a leak.
4Fix 1: Remove Sessions When They End
The direct fix is to give each session a lifetime and remove it when that lifetime ends. Logout removes the session at once. For users who just close the browser, a scheduled task removes sessions that have been idle longer than the timeout.
This works, but every developer who adds a new way to end a session must remember to call remove, and we must write and test the eviction task ourselves.
5Fix 2: A Bounded, Expiring Cache
A cache library does the lifetime management for us. Caffeine, the standard choice in Spring applications, can expire entries a fixed time after their last access and cap the number of entries, so the registry can never grow without bound, even if a code path forgets to log out.
| Option | Thread-safe | Bounded | Expires idle sessions |
|---|---|---|---|
static HashMap, no remove | No | No | No |
ConcurrentHashMap, no remove | Yes | No | No |
ConcurrentHashMap + logout + eviction task | Yes | Only by eviction | Yes, if the task runs |
Caffeine with expireAfterAccess and maximumSize | Yes | Yes | Yes |
WeakHashMap keyed by String id | No | No | Not reliably |
Caffeine is thread-safe, so this also fixes the concurrency bug. The maximum size should be chosen from capacity planning: the expected peak of concurrent sessions with a margin, times the retained size of a session, must fit comfortably in the heap. In a cluster, sessions usually belong in a shared store such as Redis through Spring Session, which also survives restarts.
6Why Weak Keys Are the Wrong Tool Here
It is tempting to use a WeakHashMap, or Caffeine's weakKeys(), so that entries disappear when their keys are no longer used. That only works when the key object's lifetime defines the entry's lifetime, for example metadata attached to an object that the rest of the program holds while it is in use. Here the key is a String id. The id string may be referenced by a cookie parser for a moment and then dropped, so the entry could vanish while the user is still active; or an interned or cached string could stay reachable forever. Either way, the key's reachability has nothing to do with whether the session is still valid. Session lifetime is a business rule, expiry after inactivity or logout, so it must be expressed as one.
7Follow-up questions
How would a heap dump show this leak?
In a tool such as Eclipse MAT, the dominator tree would show the SessionRegistry class, or the HashMap its static field holds, retaining most of the heap, often over 80 or 90 percent. The histogram would show a huge number of Session instances and HashMap$Node entries, roughly equal to the number of logins since startup. Asking for the path to GC roots from any Session would lead through HashMap$Node and the map's table to the static field SESSIONS and then to the class loaded by the application class loader. Comparing two dumps taken hours apart would show the same map growing by the number of logins in between.
How do you choose the maximum size?
From capacity planning. Estimate the peak number of concurrent sessions and add a margin, then multiply by the retained size of one session, measured with a heap dump or JOL, and check that the result fits well within the heap. If the bound is hit in normal operation, users get logged out, so it should be monitored through Caffeine's statistics.
8Conclusion
In this answer, we saw that a static map is reachable from a GC root for as long as its class is loaded, so every registered Session and everything it references stays alive, and the heap grows until OutOfMemoryError. The heap dump shows one dominator reached through the static field. HashMap is also unsafe for concurrent registration. We fixed it by removing sessions on logout and expiry, or with a Caffeine cache using expireAfterAccess and maximumSize, and saw why weak keys do not help when a String id does not define the session's lifetime.
Open with
The leak comes from reachability. SESSIONS is a static field, and static fields are GC roots for as long as their class is loaded, which for a class loaded by the application class loader means forever.
Then, if they want more
So every Session that was ever registered stays reachable through the map, and so does everything each Session references, like user data or carts. Nothing ever calls remove, so the live set grows with every login until we get OutOfMemoryError Java heap space.
In a heap dump I would expect the dominator tree to show that HashMap retaining most of the heap, and the path to GC roots for any Session going through the map's nodes to the static field.
There is also a second bug: register is called from many request threads, and HashMap is not thread-safe, so concurrent puts can lose entries or corrupt the map. To fix it, sessions need a lifetime. The simple version is a ConcurrentHashMap with removal on logout plus a scheduled task that evicts idle sessions.
The cleaner version is a Caffeine cache with expireAfterAccess, say 30 minutes, and maximumSize as a hard bound, which is thread-safe and handles expiry for us. In a cluster I would put sessions in a shared store with Spring Session.
I would not use weak keys, because the String id's reachability has nothing to do with whether the session is still valid.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- HotSpot Garbage Collection Tuning Guide, JDK 21
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "This service's heap grows until OutOfMemoryError:": https://scrivio-interview-library.netlify.app/java/garbage-collection/6a086a1901/