Skip to main content

Lesson 3 of 8

Memory Leaks - Identification & Prevention

Java's GC doesn't prevent memory leaks - it prevents dangling pointers. Memory leaks in Java occur when objects are still referenced but never used again. Common culprits: static collections, listeners not removed, ThreadLocal values not cleared, inner classes holding outer class references.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Common Memory Leak Patterns

Common Memory Leak Patterns
import java.util.*;
import java.util.concurrent.*;

public class MemoryLeaks {

    // ❌ LEAK 1: Static collection that only grows
    static final Map<String, List<Event>> eventHistory = new HashMap<>();
    static void recordEvent(String key, Event event) {
        eventHistory.computeIfAbsent(key, k -> new ArrayList<>()).add(event);
        // Never trimmed - grows indefinitely
    }
    // ✅ FIX: Use bounded cache (LRU)
    static final LinkedHashMap<String, List<Event>> boundedHistory =
        new LinkedHashMap<>(100, 0.75f, true) {  // access-ordered
            @Override
            protected boolean removeEldestEntry(Map.Entry<String, List<Event>> eldest) {
                return size() > 100;  // evict oldest when over 100 keys
            }
        };

    // ❌ LEAK 2: Listeners/callbacks not removed
    public interface CatalogListener { void onBookAdded(Book book); }
    static final List<CatalogListener> listeners = new CopyOnWriteArrayList<>();
    static void addListener(CatalogListener l)    { listeners.add(l); }
    static void removeListener(CatalogListener l) { listeners.remove(l); }
    // ✅ FIX: Always call removeListener when done (in close/destructor)

    // ❌ LEAK 3: ThreadLocal not cleared - leaks in thread pool scenarios
    static final ThreadLocal<Book> currentBook = new ThreadLocal<>();
    static void processRequest(Book book) {
        currentBook.set(book);
        // ... do work ...
        // ❌ If you forget this, the thread pool thread RETAINS the Book forever:
        // currentBook.remove();
    }
    // ✅ FIX: Always call .remove() in finally
    static void safeProcess(Book book) {
        currentBook.set(book);
        try {
            // ... work ...
        } finally {
            currentBook.remove();  // ALWAYS clean up
        }
    }

    // ❌ LEAK 4: Non-static inner class holding outer class reference
    class OuterService {
        private final List<String> data = new ArrayList<>();

        class InnerTimer {  // holds implicit reference to OuterService instance!
            void start() { /* uses OuterService.this.data */ }
        }
    }
    // ✅ FIX: Make inner class static if it doesn't need outer ref
    static class StaticHelper { /* no outer ref */ }

    // Detecting leaks:
    // 1. Add -XX:+HeapDumpOnOutOfMemoryError and analyse with Eclipse MAT
    // 2. Monitor with JConsole (heap graph) or VisualVM
    // 3. Add logging for collection sizes periodically
    // 4. Use memory profilers: YourKit, JProfiler
}

class Event { String name; long timestamp; }

Quick Quiz

Tip

Tip

Practice Memory Leaks Identification Prevention in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Memory Leaks - Identification & Prevention

Practice Task

Note

Practice Task - (1) Write a working example of Memory Leaks Identification Prevention from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Memory Leaks Identification Prevention is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done