A memory leak in Java occurs when objects are no longer needed but still remain referenced, preventing the Garbage Collector from reclaiming memory. Over time, this leads to increased heap usage and possible OutOfMemoryError.
Even though Java handles memory automatically, developers must ensure that references are properly released. Static fields, listeners, collections, and threads are frequent sources of leaks.
Click the buttons below to see how the Heap Memory behaves differently under normal conditions versus when a memory leak is present.
// Static reference prevents garbage collection
public class LeakyCache {
private static List<String> cache = new ArrayList<>();
public static void addData(String data) {
cache.add(data);
}
public static void main(String[] args) {
while (true) {
addData("Memory Leak Example");
}
}
}
This program continuously adds objects to a static list. Since the list is static, it remains in memory for the entire lifetime of the application, eventually causing heap exhaustion.
// Listener reference causes memory leak
public class EventSource {
private List<EventListener> listeners = new ArrayList<>();
public void register(EventListener listener) {
listeners.add(listener);
}
}