DEV Community

Neeraj Gahlawat
Neeraj Gahlawat

Posted on

Detecting & Fixing Memory Leaks in Java (Spring Boot) โ€” A Practical Guide

๐Ÿง  Introduction

Memory leaks are one of the most dangerous performance issues in Java applications. They silently consume heap memory, degrade performance, and eventually crash production systems.

Even though Java uses Garbage Collection, memory leaks still happen when objects remain referenced and cannot be cleaned up.

In this guide, you will learn:

โœ” What memory leaks are
โœ” How to detect them
โœ” Tools professionals use
โœ” How to fix them
โœ” A working Spring Boot demo example

๐Ÿšจ What is a Memory Leak?

A memory leak occurs when:

Objects are no longer needed but are still referenced, preventing Garbage Collection.

Over time, heap usage grows until the application throws:

java.lang.OutOfMemoryError: Java heap space

๐Ÿ”ฅ Common Causes of Memory Leaks
1๏ธโƒฃ Static Collections Holding Objects
public class CacheStore {
public static List cache = new ArrayList<>();
}

โŒ Objects never released
โœ” Heap memory keeps growing

2๏ธโƒฃ Unclosed Resources
Connection conn = dataSource.getConnection();

โŒ Connection not closed โ†’ resource leak

โœ” Use try-with-resources:

try(Connection conn = dataSource.getConnection()) {
// use connection
}

3๏ธโƒฃ ThreadLocal Misuse

Improper ThreadLocal cleanup can leak memory in thread pools.

4๏ธโƒฃ Listener & Callback References

Listeners registered but never removed remain in memory.

๐Ÿ”ฌ How to Detect Memory Leeks
โœ… Step 1: Monitor Heap Usage

Use:

โœ” JVisualVM
โœ” JConsole
โœ” Micrometer + Prometheus
โœ” Grafana dashboards

If heap memory keeps growing โ†’ leak suspected.

โœ… Step 2: Generate Heap Dump

Run:

jmap -dump:live,format=b,file=heap.hprof

โœ… Step 3: Analyze Heap Dump

Use:

๐Ÿ›  Eclipse Memory Analyzer Tool (MAT)

Open heap dump โ†’ check:

โœ” Dominator Tree
โœ” Leak Suspects Report
โœ” Objects retaining memory

๐Ÿงช Spring Boot Memory Leak Demo
Leak Code Example

@RestController
public class LeakController {

    private static final List<byte[]> memoryLeak = new ArrayList<>();

    @GetMapping("/leak")
    public String leak() {
        memoryLeak.add(new byte[1024 * 1024]); // 1MB
        return "Added";
    }
}

Enter fullscreen mode Exit fullscreen mode

Every call adds 1MB โ†’ memory grows continuously.

๐Ÿ“Š Memory Leak Behavior
BEFORE FIX

โœ” Heap usage continuously increases
โœ” GC unable to reclaim memory
โœ” Application slows down

AFTER FIX

โœ” Memory stabilizes
โœ” GC reclaims unused objects
โœ” Performance improves

๐Ÿ›  Fixing the Leak
โŒ Problem

Unbounded static list storing objects.

โœ… Solution Options

โœ” Limit cache size
โœ” Remove unused objects
โœ” Use WeakReference
โœ” Use caching libraries (Caffeine, EhCache)

Example fix:

private static final List<byte[]> memoryLeak = new ArrayList<>();

@GetMapping("/fix")
public String fix() {
    if(memoryLeak.size() > 10) {
        memoryLeak.clear();
    }
    memoryLeak.add(new byte[1024 * 1024]);
    return "Managed";
}

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ˆ Production Monitoring Best Practices

โœ” Enable GC logging
โœ” Track heap usage metrics
โœ” Set memory alerts
โœ” Run periodic heap analysis
โœ” Load test before release

๐Ÿงฐ Tools Professionals Use

โœ” VisualVM
โœ” Eclipse Memory Analyzer Tool
โœ” JProfiler
โœ” YourKit

๐ŸŽฏ Key Takeaways

โœ… Garbage Collection does NOT prevent memory leaks
โœ… Static references are common leak sources
โœ… Heap dump analysis is essential
โœ… Monitoring prevents production failures

๐Ÿ”— GitHub Demo Repository

๐Ÿ‘‰ Add your GitHub link here

Example:https://github.com/yourusername/spring-boot-memory-leak-demo

๐Ÿš€ Conclusion

Memory leaks are silent killers of application performance. By monitoring memory usage, analyzing heap dumps, and following best coding practices, you can prevent crashes and ensure system stability.

Top comments (0)