How to Prevent Memory Leak in Java: Causes and Fixes
Memory leaks in Java happen when objects are no longer needed but still referenced, preventing the garbage collector from freeing memory. To prevent leaks, always remove references to unused objects, close resources like streams, and use weak references when appropriate.
Why This Happens
Memory leaks occur when your program keeps references to objects that it no longer needs. Because Java's garbage collector only frees memory for objects without references, these unused objects stay in memory and cause leaks.
java
import java.util.ArrayList; public class MemoryLeakExample { private static final ArrayList<byte[]> cache = new ArrayList<>(); public static void main(String[] args) { while (true) { byte[] data = new byte[1024 * 1024]; // 1MB cache.add(data); // keeps adding data without removing System.out.println("Added 1MB block"); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } }
Output
Added 1MB block
Added 1MB block
Added 1MB block
... (continues until OutOfMemoryError)
The Fix
To fix memory leaks, remove references to objects when they are no longer needed. For example, clear collections or close resources properly so the garbage collector can free memory.
java
import java.util.ArrayList; public class MemoryLeakFixed { private static final ArrayList<byte[]> cache = new ArrayList<>(); public static void main(String[] args) { for (int i = 0; i < 5; i++) { byte[] data = new byte[1024 * 1024]; // 1MB cache.add(data); System.out.println("Added 1MB block"); } cache.clear(); // remove references to allow GC System.out.println("Cache cleared, memory can be freed"); } }
Output
Added 1MB block
Added 1MB block
Added 1MB block
Added 1MB block
Added 1MB block
Cache cleared, memory can be freed
Prevention
To avoid memory leaks in the future, follow these best practices:
- Always close resources like files, streams, and database connections using
try-with-resourcesorfinallyblocks. - Remove objects from collections when they are no longer needed.
- Use
WeakReferenceorSoftReferencefor caches to allow garbage collection. - Be careful with static fields holding large objects.
- Use profiling tools like VisualVM or YourKit to detect leaks early.
Related Errors
Other common memory-related issues include:
- OutOfMemoryError: Happens when the JVM runs out of heap space due to leaks or large allocations.
- StackOverflowError: Caused by deep or infinite recursion, not related to heap but still a memory problem.
- Resource leaks: Forgetting to close streams or connections can cause resource exhaustion.
Key Takeaways
Remove references to unused objects to let garbage collector free memory.
Always close resources like streams and connections to avoid leaks.
Use weak references for caches to prevent holding objects unnecessarily.
Avoid static fields holding large objects unless necessary.
Use profiling tools regularly to detect and fix memory leaks early.