Analysis of Memory Leak in Java Applications via Heap?Dump
Jayvardhan Reddy Vanchireddy
Senior Data Engineer at Cognizant?? | Ex-Honeywell | #ONO ?? | #Azure ? | #German B1 Level Certified ???? | Writer@Medium ? | #BigData Engineer ??
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)
- 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. ??
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
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
UX Design | Product Design Leader | Generative AI | Databricks | Azure | AWS | Data Analytics | UX Talks about #aiml, #generativeai,#databricks, #userexperience, and #digitaltransfomation
6 年Super bro
Application Architect | Java & Spring Boot Developer | Microservices Architecture | Cloud Enthusiast | AI/ML/NLP Innovator [email protected] ??
6 年Good one buddy.