Backend Development 9 min read

Understanding Java Memory Leaks and How to Prevent Them

This article explains what memory leaks are in Java, outlines common causes such as unreleased resources, static collections, misuse of ThreadLocal, improper variable scope, inner‑class references and off‑heap memory, and provides practical solutions and best‑practice recommendations to avoid them.

Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Understanding Java Memory Leaks and How to Prevent Them

Hello, I am mikechen. Memory leaks are a frequent online fault and a common interview topic in large tech companies; this article provides a comprehensive explanation of memory leaks and their solutions.

What Is a Memory Leak

A memory leak occurs when unused objects continue to occupy memory or their memory is not released in time, leading to wasted space.

As garbage‑collector activity increases and memory usage grows, program performance degrades and, in extreme cases, an OutOfMemoryError may crash the application.

Causes of Memory Leaks

The JVM uses reference counting and reachability analysis to decide if an object can be reclaimed; if the GC mistakenly believes an object is still referenced, it cannot be collected, causing a leak.

Consequences of Memory Leaks

Long‑running programs become sluggish and performance drops severely.

The program may crash unexpectedly.

OutOfMemoryError occurs.

Errors become chaotic and hard to diagnose.

Typical Scenarios of Memory Leaks

Below are the most common situations:

1. Unclosed Resources

Database, network, and I/O connections must be closed after use; otherwise, objects like Connection , Statement , or ResultSet remain uncollected.

Example pseudo‑code:

public void handleResource {
try {
// open connection
// handle business
} catch (Throwable t) {
// log stack
} finally {
// close connection
}
}

2. Static Collections

Static containers such as HashMap or LinkedList live as long as the program, preventing contained objects from being reclaimed before program termination.

3. Misuse of ThreadLocal

ThreadLocal often leads to hidden leaks. Example:

public void testThreadLocalMemoryLeaks {
ThreadLocal
> localCache = new ThreadLocal<>();
List
cacheInstance = new ArrayList<>(10000);
localCache.set(cacheInstance);
localCache = new ThreadLocal<>();
}

After resetting localCache , the value remains referenced by the internal ThreadLocalMap , while the key becomes a weak reference, resulting in a leak.

4. Improper Variable Scope

Variables whose scope exceeds their usage can retain objects; setting them to null after use or limiting their scope to a method helps GC reclaim memory.

public class UsingRandom {
private String msg;
public void receiveMsg() {
readFromNet(); // store data in msg
saveDB();      // persist msg
}
}

5. Inner Classes Holding Outer Instances

If a method returns an inner‑class instance that is kept long‑term, the outer class instance cannot be collected, causing a leak.

6. Off‑Heap Memory

Off‑heap memory is not managed by the GC; bugs in third‑party libraries can cause leaks there.

Solutions to Memory Leaks

1. Minimize Static Variables

Avoid static variables or set them to null after use.

2. Clarify Object Scope

Prefer local variables over member fields when possible; local variables are reclaimed automatically when the stack frame exits.

3. Reduce Long‑Lived References

Prevent long‑lived objects from holding references to short‑lived ones.

4. Use StringBuilder/StringBuffer

Frequent string concatenation with immutable String creates many temporary objects; use mutable builders to lower memory pressure.

5. Explicitly Nullify Unused Objects

Manually assign null to objects that are no longer needed to aid the GC.

6. Close All Connections Promptly

Always invoke close() on database, network, and I/O connections.

---

Bonus Offer: The author provides a 300,000‑word original collection of architecture and interview materials covering Java, multithreading, JVM, Spring, MySQL, Redis, Dubbo, middleware, and more. Interested readers can add the author on WeChat (mention "合集") to receive the resources.

JavaJVMResource ManagementBest PracticesMemory Leakthreadlocal
Mike Chen's Internet Architecture
Written by

Mike Chen's Internet Architecture

Over ten years of BAT architecture experience, shared generously!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.