A memory leak in Java occurs when objects that are no longer needed remain reachable through active references, preventing the Garbage Collector from reclaiming their memory. Over time, these unused objects accumulate, increasing memory consumption and potentially causing performance degradation or OutOfMemoryError.
Key Points: • Use tools such as VisualVM, Eclipse MAT, Java Flight Recorder (JFR), or heap dumps to identify objects occupying memory unexpectedly. • Look for common causes such as static collections, unclosed resources, listener registrations, caches without eviction policies, and long-lived references. • Remove unnecessary references, close resources properly, and use WeakReference where appropriate to allow Garbage Collection.
Example: Suppose an application stores user sessions in a static HashMap but never removes expired sessions. Even after users log out, the session objects remain in memory because the map still holds references to them, causing a memory leak.
Code Example:
import java.util.HashMap;
import java.util.Map;
public class SessionManager {
private static final Map<String, Object> sessions =
new HashMap<>();
public static void addSession(String id,
Object session) {
sessions.put(id, session);
}
// Expired sessions should be removed
public static void removeSession(
String id) {
sessions.remove(id);
}
}Interview Tip: A concise interview answer is: To analyze a memory leak, I collect heap dumps and use tools like VisualVM, Eclipse MAT, or JFR to identify objects that are retained unexpectedly. After locating the source, I remove unnecessary references, close resources properly, optimize caches, and verify through monitoring that memory is being released correctly by the Garbage Collector.