How To Remedy OutOfMemoryError: Java Heap Area – DZone – Uplaza

There are 9 varieties of java.lang.OutOfMemoryError, every signaling a singular memory-related subject inside Java functions. Amongst these, java.lang.OutOfMemoryError: Java heap area stands out as one of the prevalent and difficult errors builders encounter. On this put up, we’ll delve into the foundation causes behind this error, discover potential options, and talk about efficient diagnostic strategies to troubleshoot this downside. Let’s equip ourselves with the data and instruments to overcome this widespread adversary.

JVM Reminiscence Areas

To raised perceive OutOfMemoryError, we first want to know completely different JVM Reminiscence areas (see this video clip that provides a superb introduction to completely different JVM reminiscence areas). However in a nutshell, JVM has the next reminiscence areas:

Determine 1: JVM Reminiscence Areas

  1. Younger era: Newly created utility objects are saved on this area.
  2. Previous era: Software objects which can be dwelling for an extended period are promoted from the younger era to the outdated era. Mainly, this area holds long-lived objects.
  3. Metaspace: Class definitions, methodology definitions, and different metadata which can be required to execute your program are saved within the Metaspace area. This area was added in Java 8. Earlier than that, metadata definitions have been saved within the PermGen. Since Java 8, PermGen was changed by Metaspace.
  4. Threads: Every utility thread requires a thread stack. Area allotted for thread stacks, which comprise methodology name data and native variables are saved on this area.
  5. Code cache: Reminiscence areas the place compiled native code (machine code) of strategies is saved for environment friendly execution are saved on this area.
  6. Direct buffer: ByteBuffer objects are utilized by fashionable frameworks (i.e., Spring WebClient) for environment friendly I/O operations. They’re saved on this area.
  7. GC (Rubbish Assortment): Reminiscence required for automated rubbish assortment to work is saved on this area. 
  8. JNI (Java Native Interface): Reminiscence for interacting with native libraries and code written in different languages are saved on this area.
  9. Misc: There are areas particular to sure JVM implementations or configurations, reminiscent of the interior JVM buildings or reserved reminiscence areas, they’re categorized as “misc” areas.

What Is ‘java.lang.OutOfMemoryError: Java heap space’?

Determine 2: ‘java.lang.OutOfMemoryError: Java heap space’

When extra objects are created within the “Heap” (i.e., younger and Ood) area than the allotted reminiscence restrict (i.e., -Xmx), then JVM will throw java.lang.OutOfMemoryError: Java heap area.

What Causes ‘java.lang.OutOfMemoryError: Java heap space’?

java.lang.OutOfMemoryError: Java heap area is triggered by the JVM beneath the next circumstances:

1. Enhance in Site visitors Quantity

When there’s a spike within the site visitors quantity, extra objects will likely be created within the reminiscence. When extra objects are created than the allotted Reminiscence restrict, JVM will throw ‘OutOfMemoryError: Java heap space’.

2. Reminiscence Leak Because of Buggy Code

As a result of bug within the code, an utility can inadvertently retain references to things which can be not wanted. It might probably result in the buildup of unused objects in reminiscence, ultimately exhausting the out there heap area, leading to OutOfMemoryError.

Options for ‘OutOfMemoryError: Java heap space’

The next are the potential options to repair this error:

1. Repair Reminiscence Leak

Analyze reminiscence leaks or inefficient reminiscence utilization patterns utilizing the method given on this put up. Be sure that objects are correctly dereferenced when they’re not wanted to permit them to be rubbish collected.

2. Enhance Heap Measurement

If OutOfMemoryError surfaced due the rise within the site visitors quantity, then improve the JVM heap dimension (-Xmx) to allocate extra reminiscence to the JVM. Nevertheless, be cautious to not allocate an excessive amount of reminiscence, as it might result in longer rubbish assortment pauses and potential efficiency points.

Pattern Program Producing ‘OutOfMemoryError: Java heap space’

To raised perceive java.lang.OutOfMemoryError: Java heap area, let’s attempt to simulate it. Let’s leverage BuggyApp,  a easy open-source chaos engineering challenge. BuggyApp can generate varied types of efficiency issues reminiscent of Reminiscence Leak, Thread Leak, Impasse, and a number of BLOCKED threads. Beneath is this system from the BuggyApp challenge that may simulate java.lang.OutOfMemoryError: Java heap area when executed.

public class MapManager {      
    
    personal static HashMap
    
    public void develop() {            
       lengthy counter = 0;      
       whereas (true) {               

       if (counter % 1000 == 0) {                        
          System.out.println("Inserted 1000 Records to map!");        
       }                 
       myMap.put("key" + counter, "Large stringgggggggggggggggggggggggg" + counter);                  
       ++counter;      
    }   
   }
 }

The above program has a MapManager class that internally accommodates a HashMap object that’s assigned to the myMap variable. Inside the develop() methodology, there may be an infinite whereas (true) loop that retains populating the HashMap object. On each iteration, a brand new key and worth (i.e., key-0 and Giant stringgggggggggggggggggggggggg-0) is added to the HashMap. Because it’s an infinite loop, myMap object will get constantly populated till heap capability is saturated. As soon as the heap capability restrict is exceeded, the applying will lead to java.lang.OutOfMemoryError: Java heap area

How To Troubleshoot ‘OutOfMemoryError: Java heap space’

It’s a two-step course of:

1. Seize Heap Dump

You have to seize the heap dump from the applying, proper earlier than JVM throws OutOfMemoryError. On this put up, 8 choices to seize the heap dump are mentioned. You may select the choice that matches your wants. My favourite choice is to go the -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath= JVM arguments to your utility on the time of startup. 

Instance:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/choose/tmp/heapdump.bin

Once you go the above arguments, JVM will generate a heap dump and write it to /choose/tmp/heapdump.bin every time OutOfMemoryError is thrown.

What's Heap Dump? 

Heap Dump is a snapshot of your utility reminiscence. It accommodates detailed data 
in regards to the objects and knowledge buildings current within the reminiscence. It would inform what 
objects are current within the reminiscence, whom they're referencing, who're referencing, 
what's the precise buyer knowledge saved in them, what dimension of they occupy, are 
they eligible for rubbish assortment… They supply beneficial insights into the reminiscence 
utilization patterns of an utility, serving to builders establish and resolve memory-related
points.

2. Analyze Heap Dump

As soon as a heap dump is captured, you have to use instruments like HeapHero, JHat, and many others. to investigate the dumps.

How To Analyze Heap Dump?

On this part let’s talk about the best way to analyze heap dump utilizing the HeapHero software.

HeapHero is accessible in two modes:

  1. Cloud: You’ll be able to add the dump to the HeapHero cloud and see the outcomes.
  2. On-Prem: You’ll be able to register to get the HeapHero put in in your native machine after which do the evaluation.

Observe: I favor utilizing the on-prem set up of the software as a substitute of utilizing the cloud version as a result of heap dump tends to comprise delicate data (reminiscent of SSN, Credit score Card Numbers, VAT, and many others.), and don’t need the dump to be analyzed in exterior areas.

As soon as the software is put in, add your heap dump to the HeapHero software. The software will analyze the dump and generate a report. Let’s evaluate the report generated by the software for the above program.

Determine 3: HeapHero reporting Reminiscence downside detected

From the above screenshot, you may see HeapHero reporting that an issue has been detected within the utility and it factors out that the MapManager class is occupying 99.96% of total reminiscence. The software additionally gives an total overview of the reminiscence (Heap Measurement, Class depend, Object Rely, and many others.).

Determine 4: Largest objects within the utility

Above is the “Largest Objects” part screenshot from the HeapHero’s heap dump evaluation report. This part exhibits the most important objects which can be current within the utility. Within the majority of circumstances, the highest 2–3 largest objects within the utility are accountable for Reminiscence Leak within the utility. Let’s see what are the essential data offered on this “Largest Objects” part.

Determine 5: Largest Objects Breakdown

When you discover in #4 and #5, you may see the precise knowledge is current within the reminiscence. Outfitted with this data, you may know the most important objects within the utility and the values current within the utility. If you wish to see who created or holding on to the reference of the most important objects, you need to use the “Incoming References” function of the software. When this selection is chosen, it can show all of the objects which can be referencing the MapManager class.

Determine 6: Incoming references of the Chosen Object

From this report you may discover that MapManager is referenced by Object2, which is in flip referenced by Object1, which in flip is referenced by MemoryLeakDemo.

Video

Right here’s a video abstract of this text:

Conclusion

On this put up, we’ve lined a spread of matters, from understanding JVM reminiscence areas to diagnosing and resolving java.lang.OutOfMemoryError: Java heap area. We hope you’ve discovered the knowledge helpful and insightful. However our dialog doesn’t finish right here. Your experiences and insights are invaluable to us and to your fellow readers. We encourage you to share your encounters with java.lang.OutOfMemoryError: Java heap area within the feedback under. Whether or not it’s a singular answer you’ve found, a finest follow you swear by, and even only a private anecdote, your contributions can enrich the training expertise for everybody.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version