Member-only story
How Your Code Structure Is Causing Java Memory Leaks
Real Java Memory Leaks From Design Mistakes
Java has garbage collection. But memory leaks still happen and often, they’re your fault.
Not because you forgot to close()
a resource or kept an unused object around…
But because the way you structured your classes, reused patterns, or wired your services accidentally created object graphs that GC can’t break.
In this post, we’ll cover some real-world, design-level Java memory leaks you won’t find in textbooks, and how to fix them with actual code.
1. Singleton Holding Mutable State
Situation: You use a singleton for a service class, and accidentally store per-user or per-request state in it.
Singleton lives forever. Any object referenced inside it also lives forever. Even if you “null out” local references elsewhere, GC can’t collect the state held inside the singleton.
@Component // or any singleton service
public class SessionManager {
private final Map<String, Session> sessions = new HashMap<>();
public void register(Session s) {
sessions.put(s.id(), s);
}
}