Solving JAVA Memory leaks and understanding Garbage collection

Ketan Gupta
Jan 28, 2019 · 4 min read

This is a Simple yet effective explanation of memory leak and How and When Garbage collector runs. This small read will solve many doubts and also links are provided to Oracle Docs for further research.

Memory leak is a scenario that occurs when objects are no longer being used and the Garbage Collector is unable to remove them from Heap— because they’re still being referenced. As a result, the application consumes more and more resources — which eventually leads to a fatal OutOfMemoryError.

you can specify the initial and max heap size for your application by setting parameters :
-Xms<size>
-Xmx<size>
Xms64m -Xmx512m

JVM starts with 64M, grows (up to max ceiling of 512) if mem. requirements exceed 64.

  1. Checking memory leaks with help of Eclipse:
    Anything that implements closable (since 1.5) (e.g outputstream since 1.5) will throw a warning at you if its reference is destroyed but the object is not closed.
    In Eclipse Project > Project settings > JAVA compiler > Errors/Warning > select leak from options
  2. Review Your Code:
    Static fields : static reference persists and so the object cannot be cleared from memory.
    Daemon threads that are started outside the life cycle of a Web application are prone to memory leaks.
    Closing connection : closing all file and DB connections can prevent memory leak. Always close connection in finally block.
    Null Assignment : assign null to List, maps, etc. after they are used can also prevent memory leaks.
    AutoBoxing creates a new object every time,avoid mixing of primitive with wraper classes when passing to functions.
  3. Analyzing memory usage:
Source: Oracle

Tools like JProfiler, GC Viewer, VisualVM, JConsole helps you analyze performance of your application.
you can analyze your code by running your application with VisualVM attached to it. Then perform the task that slows down your application and analyze the “monitor” and “memory pools” tabs.
see the spikes in memory usage and press the Perform GC button which will release the memory.

Garbage collection

Java garbage collection is the process by which Java programs perform automatic memory management. The garbage collector find unreferenced objects and deletes them to free up memory.
Java garbage collection is an automatic process. The programmer does not need to explicitly mark objects to be deleted. The garbage collection implementation lives in the JVM.

The java.lang.System.gc() method runs the garbage collector.
According to Oracle:
Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.
The call System.gc() is effectively equivalent to the call:
Runtime.getRuntime().gc()

Once the object is eligible for garbage collection, it may not destroy immediately by garbage collector. Whenever JVM runs Garbage Collector program, then only object will be destroyed. But we can not expect when JVM will runs Garbage Collector.

There is no guarantee that above methods will definitely run Garbage Collector.

Some people sets the object reference to null to make it eligible for gc and use System.gc() method to remove the memory explicitly. Setting it to null is not a big deal, but calling System.gc() method will affect the system performance drastically, and must not be carried out.

Image Source www.oracle.com

Heap is broken up into smaller parts or generations. The heap parts are: Young Generation, Old or Tenured Generation, and Permanent Generation.

  1. The Young Generation is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection.
  2. The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection.
  3. The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application.

After a minor GC, when aged objects reach a certain age threshold, they are promoted from young generation to old generation.

This was a simple and small explanation of memory leaks and working of Garbage collector.
Complete working of GC and JVM generation, how objects are moved from one generation to another can be studied on Oracle docs from “here

Ketan Gupta

Written by

Software Engineer, Marketing Expert, Data Analyst — Future Entrepreneur

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade