A memory leak occurs when an application keeps data it no longer needs, reducing the free memory available over time. In a JVM application, lingering references can prevent garbage collection (GC) from removing unused objects. The application may slow down or eventually fail with an OutOfMemoryError. section 6.1.1 section 6.2.3
A list that never releases objects
A Java application repeatedly creates Cat objects and adds them to a static list without removing them. The list retains their references, so GC cannot reclaim the objects. As the list grows, the heap eventually fills. section 6.2.3
Listing 6.7 Producing an OutOfMemoryError
public class Main {
public static List<Cat> list = new ArrayList<>();
public static void main(String[] args) {
while(true) {
list.add(new Cat(new Random().nextInt(10))); #1
}
}
}
See the loop that continually adds objects to the retained list. section 6.2.3
To investigate a running application, watch memory usage in VisualVM. A healthy application can show peaks as it allocates memory and valleys as GC frees it. With a leak, GC may free too little while used memory keeps rising; GC activity may also intensify. section 6.2.3
Figure 6.12 A comparison between the memory usage for a healthy app versus an app suffering from a memory leak. The GC manages to free unneeded data from memory for a healthy app, and the allocated space never fills up. An app suffering from a memory leak doesn’t allow the GC to remove enough data. At some point, the memory fills up completely, generating an OutOfMemoryError.
Compare the memory graphs of a healthy application and one affected by a leak. section 6.2.3
An OutOfMemoryError is a clue, not necessarily the location of the leak. One thread can retain the objects while another encounters the error when it tries to allocate memory. Use a heap dump to investigate the root cause; a dump is also useful when the application has crashed or cannot be profiled. section 6.2.3 section 11.2





