Memory Leak in Java
Java provides out-of-box memory management. When we create an object using the new keyword, the JVM automatically allocates memory for that object. If the object is no longer is used by the application, the garbage collector automatically removes that object and free up space for other applications. Therefore, the programmer need not to manage memory manually like other procedural programming languages (C, and C++). Nevertheless, there is a chance of memory leak in a Java application. In this section, we will understand what is a memory leak in Java, its causes, detect and fixing of memory leaks.
What is memory leak in Java?
In Java, the memory leak is a situation when the garbage collector does not recognize the unused objects and they remain in the memory indefinitely that reduces the amount of memory allocated to the application. Because the unused objects still being referenced that may lead to OutOfMemoryError. It also affects the reliability of the application. The following figure represents the memory leak.
Note: We can specify the initial and maximum heap size for the application. There are the two parameters (options) for setting up the heap size:
Where m denotes the size in MB.
Symptoms of Memory Leak
If any Java application suffers from a memory leak, you notify the following things:
Causes of Memory Leaks
There are the following causes of memory leaks in Java:
Preventing Memory Leak
While writing code, remember the following points that prevent the memory leak in Java.
Creating Memory Leak
Let's create a simple Java program that creates a memory leak.
In the above program, we have created two Vector objects and passed large numbers to them. When we run the above program, it shows java.lang.OutOfMemoryError. Because it does not occupy space in the memory. If the program prints the statement There is no memory leak in this program, it ensures that the program runs successfully.
Detecting Memory Leak
Detecting memory leaks is a difficult task. To simplify the task, there are many tools available that perform static analysis and detect memory leaks:
Fixing Memory Leak
There are the following solutions to the memory leak problem: