Common reasons for memory leaks

The following are the most common reasons for memory leaks:

  • Open streams: While working on streams and readers, we often forget to close the streams, which eventually results in the memory leak. There are two types of leaks that result from unclosed streams—low-level resource leak and memory leak. Low-level resource leak includes OS-level resources, such as file descriptor and open connection. As JVM consumes memory to track these resources, it leads to memory leak. To avoid leaks, use the finally block to close the stream or use the autoclose feature of Java 8.
  • Open connections: We often forget to close opened HTTP, database, or FTP connections, which results in the memory leak. Similar to closing streams, close the connections.
  • Static variables referencing instance objects: Any static variable referencing a heavy object could lead to memory leak because even if the variable is not in use, it won't be garbage collected. To prevent this, try not to have heavy static variables; use local variables instead.
  • Missing methods for objects in collection: Adding objects having no implementation of the equals and hashcode methods to HashSet will add the number of duplicate objects in HashSet and we would not be able to remove these objects once added. To prevent this, implement the equals and hashcode methods in the object added to HashSet.

Diagnosing memory leaks is a lengthy process that requires a lot of practical experience, debugging skills, and detailed knowledge of the application. The following are the ways to diagnose memory leaks:

  • Enable GC logs and fine-tune GC parameters
  • Profiling
  • Code review

In the following sections, we will see GC's common pitfalls, GC methods, and tools to analyze GC logs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset