Leaks from static collections and caches
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Most real Java leaks are not exotic. They are a static list or map, or a cache that lives as long as the application, which gains an entry on every request and loses none.
Static lists and maps live as long as the class
A static field belongs to the class, not to any object, and the class keeps it reachable for as long as the class is loaded. For classes loaded by the application class loader, that is normally the whole run of the program.
Example 1 · A static audit log that outlives everyone
import java.util.ArrayList;import java.util.List;
class Audit { // A static field is reachable from the Audit class itself, for as long as the class is loaded. static final List<String> entries = new ArrayList<>();
static void record(String user, String action) { entries.add(user + " " + action); }}
class AttendanceService { void markPresent(String roll) { // A local list: it dies when the method returns. List<String> temp = new ArrayList<>(); temp.add(roll); Audit.record("teacher-7", "marked " + roll); }}
public class AuditLogLeakDemo { public static void main(String[] args) { AttendanceService service = new AttendanceService(); for (int day = 1; day <= 3; day++) { for (int i = 1; i <= 2000; i++) { service.markPresent("R" + i); } System.out.println("Day " + day + ": audit entries in memory = " + Audit.entries.size()); } service = null; // the service is gone... System.out.println("Service dropped, entries still reachable = " + Audit.entries.size()); }}Day 1: audit entries in memory = 2000 Day 2: audit entries in memory = 4000 Day 3: audit entries in memory = 6000 Service dropped, entries still reachable = 6000
What this code does
- The local list
tempdies whenmarkPresentreturns, but every call also adds a line toAudit.entries, a static list. After three days 6,000 entries are reachable from theAuditclass. - Setting
service = nullfrees only the service object. The entries were never owned by it: the static field keeps all of them alive until the class is unloaded, which here means never.
So everything you put into a static collection stays until your code removes it. Static collections are tempting because any code can reach them: an audit log, a list of "recent" items, a registry of handlers. The leak starts when the code that adds is busy (every request, every row) and nobody owns the removing. Notice in the example that dropping the service object changes nothing. The entries are held by the Audit class, not by the service that created them.
Unbounded caches keyed by user or session
An unbounded cache is a map with no size limit and no rule for removing entries, so it grows with every different key it has ever seen.
An unbounded cache is a map with no size limit and no rule for removing entries. It grows with the number of different keys it has ever seen.
Example 2 · A cart map keyed by session id
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
class Cart { final List<String> items = new ArrayList<>();}
class ShopApp { // session id -> cart. Every visit gets a new session id, even for the same person. static final Map<String, Cart> carts = new HashMap<>(); static int nextSession = 1;
static String openShop() { String sessionId = "sess-" + nextSession++; carts.put(sessionId, new Cart()); return sessionId; }
static void addItem(String sessionId, String item) { carts.get(sessionId).items.add(item); }
static void checkout(String sessionId) { }}
public class GuestCartLeakDemo { public static void main(String[] args) { for (int hour = 1; hour <= 3; hour++) { for (int visit = 0; visit < 5000; visit++) { String s = ShopApp.openShop(); ShopApp.addItem(s, "USB Cable"); if (visit % 2 == 0) { ShopApp.checkout(s); // half the visitors buy } // the other half just close the app } System.out.println("Hour " + hour + ": carts in memory = " + ShopApp.carts.size()); } }}Hour 1: carts in memory = 5000 Hour 2: carts in memory = 10000 Hour 3: carts in memory = 15000
What this code does
- Every visit creates a new session id and a new cart. Neither checkout nor leaving the app removes the cart, so the map gains 5,000 entries an hour, forever.
- In a real online shop with lakhs of visits a day, this is exactly the slow climb of the after-GC heap from the first lesson of this module.
Example 3 · A cache key that is unique per request
import java.util.HashMap;import java.util.Map;
public class RequestKeyCacheDemo { static final Map<String, String> resultCache = new HashMap<>(); static int hits = 0; static int requestCounter = 0;
// BUG: the key includes the request number, so no two requests share a key. static String resultWrong(int roll) { String key = roll + "#" + (++requestCounter); String cached = resultCache.get(key); if (cached != null) { hits++; return cached; } String result = "Result of " + roll; // pretend: slow database query resultCache.put(key, result); return result; }
public static void main(String[] args) { // 100 students check their results 30 times each on result day. for (int round = 0; round < 30; round++) { for (int roll = 1; roll <= 100; roll++) { resultWrong(roll); } } System.out.println("Requests: 3000, cache hits: " + hits + ", cache size: " + resultCache.size()); }}Requests: 3000, cache hits: 0, cache size: 3000
What this code does
- The key
roll + "#" + requestNumberis different for every request, so even the 30th lookup for the same roll misses. The cache has 3,000 entries and 0 hits: all cost, no benefit. - The key must contain only what decides the answer, here the roll number. Then the same 3,000 requests give 2,900 hits with 100 entries.
If the key is a user id, it grows with your user base; if the key is a session id, a guest token or a request id, it grows with every visit, which never stops. Two patterns are especially bad. Keys that are new on every visit (session ids for guests who never log out) make the map grow without bound. Keys that include something unique per request (a timestamp, a request counter, a random id) make the cache useless and leaky at once: no lookup ever hits, yet every lookup adds an entry. Before you add a cache, ask two questions: how many different keys can there be, and what removes an entry?
Mutable keys in a HashMap that can never be removed
A HashMap finds an entry by the key's hashCode(), then confirms it with equals(). If you change a field used by those methods after the key is in the map, the entry stays in the bucket for the old hash code.
Example 4 · A mutable key gets stuck in a HashMap
import java.util.HashMap;import java.util.Map;import java.util.Objects;
class Seat { String coach; // mutable, and used in equals/hashCode int number;
Seat(String coach, int number) { this.coach = coach; this.number = number; }
@Override public boolean equals(Object o) { return o instanceof Seat s && s.coach.equals(coach) && s.number == number; }
@Override public int hashCode() { return Objects.hash(coach, number); }}
public class MutableKeyDemo { public static void main(String[] args) { Map<Seat, String> booked = new HashMap<>(); Seat seat = new Seat("S4", 32); booked.put(seat, "PNR-881"); System.out.println("Booked: " + booked.size() + ", found: " + booked.containsKey(seat));
seat.coach = "S5"; // coach changed AFTER the seat was used as a key System.out.println("After change, found: " + booked.containsKey(seat)); System.out.println("remove(seat) returned: " + booked.remove(seat)); System.out.println("Remove with old values: " + booked.remove(new Seat("S4", 32))); System.out.println("Entries stuck in the map: " + booked.size()); }}Booked: 1, found: true After change, found: false remove(seat) returned: null Remove with old values: null Entries stuck in the map: 1
What this code does
- After
seat.coachchanges,containsKey(seat)looks in the bucket for the new hash code and finds nothing, soremove(seat)returnsnull. - A new
Seat("S4", 32)reaches the right bucket, butequalscompares it with the changed key (now S5) and fails. No key can reach the entry any more, yet it is still counted insize().
Lookups with the changed object search the wrong bucket, and lookups with an object equal to the old values reach the right bucket but fail equals against the changed key. The entry is now unreachable by key but still in the map: get, containsKey and remove all miss it, and it stays until the whole map is cleared. In a long-lived map, every such change is a small permanent leak. Fix: use keys that cannot change. A String id, an Integer roll number, or a record with final fields makes a safe key; key by the stable id rather than by a whole mutable object.
Fixes: limits, eviction and removing entries
Every long-lived collection needs an answer to "what removes an entry?". There are three standard answers, and a robust store often uses all three.
Example 5 · Three fixes in one session store
import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Map;
class SessionStore { private static final long IDLE_LIMIT = 30; private static final int MAX_SESSIONS = 3;
private final Map<String, Long> lastSeen = new LinkedHashMap<>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<String, Long> eldest) { return size() > MAX_SESSIONS; // fix 2: a hard limit } };
void touch(String session, long now) { lastSeen.put(session, now); }
void logout(String session) { lastSeen.remove(session); // fix 1: remove when done }
void expire(long now) { // fix 3: evict idle entries Iterator<Map.Entry<String, Long>> it = lastSeen.entrySet().iterator(); while (it.hasNext()) { if (now - it.next().getValue() > IDLE_LIMIT) { it.remove(); } } }
@Override public String toString() { return lastSeen.keySet().toString(); }}
public class ExpiringCacheDemo { public static void main(String[] args) { SessionStore store = new SessionStore(); store.touch("asha", 0); store.touch("ravi", 5); store.touch("meena", 10); System.out.println("t=10 " + store);
store.logout("ravi"); System.out.println("t=12 after ravi logs out: " + store);
store.touch("kiran", 20); store.touch("john", 25); System.out.println("t=25 after 2 more logins (limit 3): " + store);
store.touch("kiran", 50); store.expire(50); System.out.println("t=50 after expiring idle > 30 min: " + store); }}t=10 [asha, ravi, meena] t=12 after ravi logs out: [asha, meena] t=25 after 2 more logins (limit 3): [meena, kiran, john] t=50 after expiring idle > 30 min: [john, kiran]
What this code does
logoutremoves Ravi at once. When the third and fourth new logins arrive, the limit of 3 evicts Asha, the least recently active, even though she never logged out.- At minute 50,
expireremoves Meena, idle for 40 minutes, and keeps John (25) and Kiran (0). The store can never grow beyond 3 entries, and idle entries cannot stay for ever.
- Remove when done:
removeon logout, on checkout, after an OTP is used. The cheapest fix, when there is a clear end event. - A size limit: an LRU map with
removeEldestEntry, or a bounded deque. Memory is capped even when nobody logs out. - Time-based expiry (TTL, time to live): store a timestamp with each entry and remove entries older than a limit, on access or in a periodic cleanup.
- Do not store it: keep a count or a total instead of whole objects, or use local variables that die with the method.
Find the bug
Find the line that leaks
Tap the line that makes memory grow forever, then check the fix.
A cart is created when a visitor opens the shop. Visitors leave.
Round 1 of 3Next step
Check your understanding
12 quick questions