☕ Java Advanced

What is a memory leak in Java and how do you prevent it?

Answer

A memory leak in Java occurs when objects that are no longer needed remain referenced and cannot be garbage collected. Despite automatic GC, Java can still leak. Common causes: static fields holding collections that grow indefinitely, listeners/callbacks not deregistered after use, caches without eviction policies, long-lived objects holding references to short-lived ones (e.g., a static reference to an Activity in Android), and non-closed resources (streams, connections). Detection: heap dump analysis with Eclipse MAT or YourKit, monitoring heap growth with -verbose:gc. Prevention: use WeakReference for caches, remove listeners when done, use try-with-resources for I/O, and use profilers to catch leaks early in development.