Are you bored to see this (java.lang.OutOfMemoryError) again & again on your screen? But, do you know what the reason for this error is? If not, it is a must for you to know about this. This (java.lang.OutOfMemoryError) error is shown when there are memory leaks in Java. And, because of the Java memory leaks, sometimes your program is stuck.
Java Memory Leaks is a genuine problem. If you want to execute your program without facing this kind of problem, then we’ll help you to learn about memory leaks in Java & how to fix them or avoid them.
What is Memory Leaks In Java?
Memory leak is a situation when there is no use of objects, but the garbage collector is unable to remove them from the memory because they are still referenced.
|NOTE:- About Garbage Collector?|
Java itself manages the memory & for that, it provides the automatic garbage collector. Garbage collector assures that all the unusual space gets removed and memory can be free.
If you are a programmer, then memory leaks in Java are bad for you because it blocks the memory resources & reduce system performance with time. If not dealt with, the system shows java.lang.OutOfMemoryError error.
For a better understanding of the Java memory leaks concept, go through with the below presentation:
As the presentation shows, there are two types of objects-referenced and unreferenced. The garbage collector removes the unreferenced objects, and Referenced objects won’t be collected & removed. Even if the application does not use them.
Types Of Memory Leaks in Java
There are numerous reasons for Java memory leaks in any application. In this section, we’ll discuss the reasons:
Through static Fields
In Java, the heavy use of a static variable is a reason for a memory leak. The static field usually remains in memory till then the application is running. Here’s the example:
The addIntegers() method populates a static List object in this program, which remains in memory during program execution. This means the garbage collector does not remove the memory consumed by the list.
How to prevent it?
- The use of static fields should be minimized to prevent memory leaks in Java.
- When using singletons, rely on the lazy load design pattern so that resources are only configured when needed.
Through Unclosed Resources:
Whenever we make new resources such as connections and streams, the JVM allocates memory to these resources. If these resources are not closed, the memory allocated to these resources is blocked, and the garbage collector cannot free up this space.
How to prevent it?
- If the resources are no longer needed, they should be closed with the final block.
- The code used to close the resources should not have any exceptions.
- We can prevent java memory leaks with the use of try-with-resources blocks.
Improper equals() and hashCode() Implementations:
When creating a new class, if you are not using a proper implementation of equals() & hashcode() methods, this will lead to new memory leaks in java. Here’s an example:
In this example, duplicate entries can be added if the class is used as a key for the Hashmap or HashSet. There is no method to discover how two objects should be considered equal.
The map object will include 10000 entries for the same key in the above program. The map doesn’t allow duplicate keys. These duplicate keys are added up and block the memory, and the garbage collector is ineligible to remove them.
HashSet & Hashmap uses this method for many operations. If they are not overriding correctly, they can become a reason for potential memory leaks in java.
How to prevent it?
- When defining a new class it always overrides equals() & hashcode() methods.
- Overriding is not just enough; optimally implementing these methods to properly utilize resources and memory.
How to avoid memory leaks in Java?
To avoid Java memory leaks, you need to pay attention to the ways by which these leaks can be minimized. Some of the most common ways are:
Use reference objects to avoid memory leaks:
We can resort to referencing objects in Java using the java.lang.ref package. With the use of java.lang.ref package, you can work with garbage collectors in your program. Instead of directly referencing objects, We use special reference objects that the garbage collector easily clears.
We can work with the garbage collector to automate the task using reference objects. The garbage collector automatically removes listeners that are weakly reachable.
Verbose Garbage Collection
If you want to obtain a detailed trace of the garbage collector, you can enable verbose garbage collection. To enable verbose garbage collection, we need to add a parameter in our JVM configuration.
After adding this parameter, we can see the details of the garbage collector.
By enabling Memory Profilers
Memory profilers are tools that can monitor memory usage and detect java memory leaks in any application. The Java profilers can also help to analyze how memory is allocated. Several tools like- Java VisualVM, JProfiler, and YourKit, can be used for memory profiling in Java.
There are more several ways to avoid memory leaks in Java, and these are:
|Using Heap dumps|
|Eclipse Memory Leak Warnings|
Memory leaks in Java are considered a disease because they block the performance of the resources. If they can not fix or avoid on time, it can result in fatal application crashes over time.
Java memory leaks can use the production code as an unnerving experience. The leaks can be hard to find & minimize. But if we regularly perform accurate code, we can minimize the risk of memory leaks in Java.
Frequently Asked Questions
- What is Heap Memory?
Heap memory is a run-time data area that stores the actual object in memory. When the Java virtual machine start-ups, the heap memory is created. Heap memory may increase or decrease when the program executes.
- What are memory leaks in Java?
A memory leak is a situation when there is no use of objects, but the garbage collector is unable to remove them from the memory because they are still referenced.