Analysis of Memory Leak in Java Applications via Heap?Dump

Memory plays a vital role in any application performance and we cannot afford to waste the resources unnecessarily, as it involves both time and money which is a major factor in any real time application. A application is said to utilize the resources efficiently, when the application developers keep the memory as a constraint while designing it. In most cases the developers are either unaware or ignore these factors while coding. In this article we will learn the best practices to code efficiently and the factors that are involved in memory leak.

What is Memory Leak?

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

Before we proceed any further, you will need to have a basic idea on the tools that help us in analyzing these memory leaks. Please click link below.

Heap dump generation & Analysis Tools

Scenario’s resulting in Memory Leaks

Java Heap Leaks (OutOfMemoryError)

  1. Objects are continuously instantiated without being released:

This occurs when an infinite loop of objects are being instantiated, while the memory is not being released as the current thread is still performing the operations. For this example, we can change the Java Heap size to 32m by setting the –Xms and –Xmx virtual machine arguments. Here -Xms stands for initial size (bytes) of the java heap, -Xms for maximum size, in bytes, of the memory allocation pool.

If you want a heap-dump on out-of-memory, you can start Java with virtual machine arguments option as

Under Run configuration we are setting the heap size to 32 Mb . Open the tab Arguments and add the parameters-Xmx32min the VM arguments section. You might want to set the -Xms32m as well (small heap size).

A sample Program to Generate OutOfMemoryError

Infinite instantiation of objects using while Loop that results in OutOfMemoryError. On executing the program you will get a Run-time Exception.

In this case the Heap Dump is generated in your default work-space directory. You can also set the path explicitly by adding the parameter under VM Arguments.

Using the JVisualVM tool to analyze heap-dump.

The figure below will show the amount of size that was allocated and retained which caused the OutofMemoryError. Select Object Drop-down in the JvisualVM tool to know number of instances created & size occupied.

The Objects which are not yet Garbage collected.

Using JMAT Tool to Analyze Heap Dump

On opening Heap dump the Overview tab shows the below information.

You can click on the Histogram to Obtain the class class hierarchy which shows the class name, Objects and the heap status.

You can Scroll down under Overview tab and then click on Leak Suspects to find the details as shown in below screenshots to pinpoint the class responsible for OutOfMemoryError and the number of Objects that was created.

2. Unclosed Connections (DataBase Leak):

When someone is trying to establish a connection to the database but not closing it. This would be indicative of someone making use of a getConnection(), and then not closing the connection when completed. For instance, if someone had a close() in a try {} block, but they didn’t put in the finally {} section. As such, you are leaking connections, and when someone goes to the pool to get a connection, the pool blocks you because all available connections are in use.

When we look into the dump on this server, looks like most of the thread is waiting for the dbconnection.

Due to DataBase Leak we are unable to Obtain new connection to it, as all the resources are currently being used.

We can avoid this by closing connection in finally block.

3. Static Field holding on to the Object Reference:

It is caused by referencing a heavy object with a static field.

We created our ArrayList as a static field — which will never be collected by the JVM Garbage Collector during the lifetime of the JVM process, even after the calculations it was used for are done. We also invoked Thread.sleep(10000) to allow the GC to perform a full collection and try to reclaim everything that can be reclaimed.

4. Adding Objects with no hashCode() and equals() into a HashMap:

when we start adding duplicate objects into a Map, this will only ever grow, instead of ignoring duplicates as it should.

You can prevent this by Overriding the hashcode and equals method to prevent duplicate Objects from being inserted.

verbose: One of the quickest ways to identify a memory leak is to enable verbose garbage collection. It gives you a detailed trace of GC summary report. You can add the option under VM arguments.

Now that you have reached so far, why don't you try it out yourself. Below is the link to my GIT- repository.

If you enjoyed reading it ,you can click the like, share button and let others know about it. If you would like me to add anything else, please feel free to leave a response. ??

Giri Shankar Ravichandran

Performance Tester | MS-AZ900 | ISTQB -CTFL-AGILE | Neotys Neoload -HP Load Runner - Certified

6 年

Hi jayvardhan I could see the gc allocation failure and gc ergonomics in the gc log of our servers...could you please explain those and does it cause for performance degradation

chidananda U

UX Design | Product Design Leader | Generative AI | Databricks | Azure | AWS | Data Analytics | UX Talks about #aiml, #generativeai,#databricks, #userexperience, and #digitaltransfomation

6 年

Where are u

回复
chidananda U

UX Design | Product Design Leader | Generative AI | Databricks | Azure | AWS | Data Analytics | UX Talks about #aiml, #generativeai,#databricks, #userexperience, and #digitaltransfomation

6 年

Super bro

回复
Dhananjaya Naidu Reddi

Application Architect | Java & Spring Boot Developer | Microservices Architecture | Cloud Enthusiast | AI/ML/NLP Innovator [email protected] ??

6 年

Good one buddy.

要查看或添加评论,请登录

Jayvardhan Reddy Vanchireddy的更多文章

  • Apache Spark-3.0 Sneek peak

    Apache Spark-3.0 Sneek peak

    Apache Spark has remained strong over the years and now is coming back with one of its major releases with its ongoing…

    14 条评论
  • Working of Sqoop Incremental Load

    Working of Sqoop Incremental Load

    In my series of BigData Architecture, we have seen the internal working of Sqoop. Now as part of this article, we'll…

    3 条评论
  • Deep-dive into Spark Internals & Architecture

    Deep-dive into Spark Internals & Architecture

    Apache Spark is an open-source distributed general-purpose cluster-computing framework. A spark application is a JVM…

    12 条评论
  • Sqoop Architecture in Depth

    Sqoop Architecture in Depth

    Apache Sqoop is a data ingestion tool designed for efficiently transferring bulk data between Apache Hadoop and…

    9 条评论
  • HDFS Architecture in Depth

    HDFS Architecture in Depth

    Hadoop consists of mainly two main core components HDFS, MapReduce. HDFS is the Hadoop Distributed File System ( HDFS )…

    3 条评论
  • Hive Architecture in?Depth

    Hive Architecture in?Depth

    Apache Hive is an ETL and Data warehousing tool built on top of Hadoop for data summarization, analysis and querying of…

  • Application Development: 4 Simple Steps to Resolve Remote Debugging Connection Problems

    Application Development: 4 Simple Steps to Resolve Remote Debugging Connection Problems

    As a developer, we frequently debug the application during the development activities. The real time applications are…

    1 条评论
  • 5 Useful Tools for a Full-stack Developer

    5 Useful Tools for a Full-stack Developer

    The below tools will help you increase your productivity and reduce compilation issues on running a debug job…

    1 条评论
  • Database Transaction Leak in Java Application

    Database Transaction Leak in Java Application

    In a real time application the Database leak occurs due to Unclosed transactions created by the programmers. The stakes…

    1 条评论
  • Heap dump generation & Analysis using JMAP, JMAT, JvisualVM Tools

    Heap dump generation & Analysis using JMAP, JMAT, JvisualVM Tools

    Every Programmer is bound to use these tools at some point of time, As it plays a vital role in optimizing the…

社区洞察

其他会员也浏览了