Home » Core Java » Memory Leak in Java

About Yatin

Avatar photo
An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Memory Leak in Java

Hello. In this tutorial let us learn about memory management and memory leaks in a java programming language.

1. Introduction

Memory management in java is an interesting concept where the memory is divided into three different parts.

Fig. 1: Memory management in java

Let us understand each part separately.

1.1 Young generation

The young generation refers to a place where new objects are created and when it is overloaded garbage collection takes place. The garbage collection is known as Minor GC. This generation is divided into 3 parts i.e. Eden memory and two Survivor spaces. During the minor gc process, all the survivor objects are moved to one of the survivor spaces. Objects that survive many cycles of garbage collection are moved to the old-generation memory space. In minor gc, all the application threads are stopped until the garbage collection operation is completed.

1.2 Old generation

The old generation is the one where long-lived objects live. When the objects reach a certain age threshold after multiple garbage collection events they are moved to the old generation. When the objects are collected from the old generation a major garbage collection event occurs. Garbage collection is performed in an old generation when the space is full and it is a slow process because it involves all live objects.

1.3 Permanent generation

A permanent generation or Perm gen contains the application metadata required by the java virtual machine to describe the classes and methods used in the application. This generation is not a part of java heap memory and is populated by a java virtual machine at runtime based on the classes used by the application. It also contains the java library classes and methods. The objects lying in a permanent generation are garbage collected in a full garbage collection. This was replaced by metaspace in java8.

2. Memory leak in java

A memory leak in java occurs when the garbage collection is unable to remove the unused objects and they remain in memory for an indefinite period. These unused objects lead to the out of memory errors and affect the application’s reliability. The different types of memory leaks are –

  • The usage of static fields in an application could cause memory leaks as they belong to the application life span
  • Stream I/O connections are not closed and memory allocated to these resources is still blocked and garbage collection is unable to free up this space
  • hashCode() and equals() methods implementation is not done correctly

2.1 Symptoms

Memory leaks in any application can occur because of the following reasons –

  • Performance degradation when an application is running continuously for a long time
  • Out-of-memory heap error
  • An application running out of connection string objects
  • Frequent application crashes

2.2 Causes

Memory leaks in java occur because of the following reasons –

  • Unwanted object references are being still used in an application and the garbage collector failed to reclaim the memory
  • Using static objects because they are available throughout the application’s lifespan
  • Daemon threads started outside of the application lifecycle
  • Using reference objects to avoid memory leaks
  • Usage of java native interface in an application and failure to clean up for these resources
  • Bugs in AWT and Swing packages

2.3 Detect

Detecting a memory leak in an application can be done with the help of the following techniques –

  • Memory profilers are used to monitor memory usage in an application and help detect memory leaks in an application. They have to gauge how much memory and cpu is being used by each method
  • The -verbose:gc flag can be used to generate a detailed trace of the java garbage collector. The default error output shows the summary to understand the memory and identify or manage the memory leaks
  • Heap dumps can be used to provide a snapshot of the heap memory of an application at a particular time. This information is helpful to identify the count of created object instances and if any of them causing any memory leaks

2.4 Prevent

Memory leaks can be avoided by –

  • Using the java virtual tools to optimize the code and show the memory status
  • Using the heap dump to create a snapshot of all objects that reside in the memory at a given time
  • Using a try-with-resources block to free up the objects or resources when their job is done
  • Clean the HttpSession in the Java EE application with the help of HttpSession.invalidate() method
  • Avoid string concatenation and prefer using StringBuffer.append() method
  • If the application has a connection to a database do not use * in the sql query and prefer using particular column names

3. A sample program that could cause a memory leak

The below program in java can help to cause a memory leak as we have created two vector objects and passed a large value to them. The execution of this program will result in a java.lang.OutOfMemoryError. If there is no memory leakage the logger message will be printed on the console.

GCError.java

import java.util.Vector;

public class MemLeakEx {

    public static void main(String[] args) {
        final Vector vector1 = new Vector(314567);
        final Vector vector2 = new Vector(784324678);

        System.out.println("No memory leak occurred in the program");
    }
}

Once the class runs an error like below will be thrown.

Fig. 2: Error output

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

4. Summary

In this tutorial, we learned about memory management and memory leaks in java. You can download the source code from the Downloads section.

6. Download the Project

This was a tutorial to understand memory management and memory leaks in java.

Download
You can download the full source code of this example here: Memory Leak in Java

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments