JVM.GC.Avoiding Memory Leaks in Large Collections

Large collections such as HashMap, ArrayList, and Set can hold references to objects even after they are no longer needed. If the objects are strongly referenced inside these collections, they cannot be garbage collected, leading to memory leaks.

1️⃣ The Problem: Strong References in Collections

  • If you store objects in a HashMap, ArrayList, or other collections, they are strongly referenced by default.
  • Even if you set the original reference to null, the object remains in the collection, preventing garbage collection.

Example: Memory Leak Due to Strong References

import java.util.HashMap;
import java.util.Map;

public class StrongReferenceCollectionExample {
    public static void main(String[] args) {
        Map<Object, String> map = new HashMap<>();
        Object key = new Object();
        map.put(key, "Data");

        key = null; // Remove strong reference

        System.gc(); // Suggest GC

        System.out.println("Map size: " + map.size()); // The key is still in the map!
    }
}

Why Does This Cause a Memory Leak?

  • Even though key = null;, the HashMap still holds a reference to the object.
  • The object cannot be garbage collected because the map prevents it from being freed.

2️⃣ The Solution: Using WeakHashMap

A WeakHashMap automatically removes entries whose keys are only weakly referenced, preventing memory leaks.

Example: Fixing Memory Leak with WeakHashMap

import java.util.WeakHashMap;

public class WeakHashMapExample {
    public static void main(String[] args) {
        WeakHashMap<Object, String> weakMap = new WeakHashMap<>();
        Object key = new Object();
        weakMap.put(key, "Cached Data");

        key = null; // Remove strong reference

        System.gc(); // Suggest GC

        System.out.println("Map size: " + weakMap.size()); // Might be 0 if GC removed it
    }
}

Why Does This Work?

  • Since WeakHashMap stores keys as weak references, once the original reference (key) is removed, the object becomes eligible for GC.
  • If GC runs, the entry is automatically removed from the map.
  • No memory leak!

3️⃣ Using WeakReference in Large Collections

If you’re using lists or other collections, you can use WeakReference instead of WeakHashMap.

Example: Avoiding Memory Leak in List

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class WeakReferenceListExample {
    public static void main(String[] args) {
        List<WeakReference<Object>> list = new ArrayList<>();
        Object obj = new Object();
        list.add(new WeakReference<>(obj));

        obj = null; // Remove strong reference

        System.gc(); // Suggest GC

        list.removeIf(ref -> ref.get() == null); // Clean up collected references

        System.out.println("List size: " + list.size()); // Might be 0 if GC ran
    }
}

Why Does This Work?

  • The list holds WeakReference<Object> instead of a strong reference.
  • When GC runs, the referenced object is removed.
  • We clean up null references using list.removeIf(ref -> ref.get() == null).

4️⃣ Summary: How Weak References Prevent Memory Leaks in Large Collections

Collection TypeProblem with Strong ReferencesSolution Using Weak References
HashMap<Object, String>Entries stay in memory even after the key is set to null.Use WeakHashMap<Object, String>, so keys are collected when unused.
ArrayList<Object>Objects in the list prevent GC, causing memory buildup.Store WeakReference<Object> in the list instead.
Set<Object>Objects persist in memory after use.Use WeakReference to allow GC cleanup.

5️⃣ Conclusion

  • Large collections holding strong references can prevent GC from reclaiming memory.
  • Weak references (WeakHashMap or WeakReference) allow GC to remove unused objects.
  • This helps prevent memory leaks, especially in caching, listener patterns, and large collections.

📌 In short: Weak references allow collections to automatically clean up unused objects, preventing memory leaks! 🚀

This entry was posted in Без рубрики. Bookmark the permalink.