How to fix java heap space error?

jamerober

Member
My application crashes with java heap space error under normal load looks like an OutOfMemoryError. I’m not sure whether to raise the JVM -Xmx, profile for leaks, or refactor the code. What practical steps helped you identify and fix heap issues?
 
In fact, the first thing I do is to check whether or not it is actually a memory leak. Occasionally individuals simply continue increasing -Xmx until it seems an enchanted spell, however when your application is object leaking you will only be pushing off the crash. Such tools as VisualVM or YourKit can assist you in identifying the objects that are consuming a lot of memory. Subsequently, I tend to optimize collections and caches, occasionally all one needs to do is to clean up references.
 
I've been there . Increasing -Xmx is a temporary solution which should not be used indefinitely. I normally begin with profiling either Eclipse MAT or VisualVM. There was an instance when I discovered some massive HashMap that was not cleared after repairing it, the heap stabilized. In addition, look for streams and huge lists that continue to accumulate.
 
Raise -Xmx? And anybody can have a limitless RAM. As a matter of fact, occasionally your normal load is not that normal.😭 One of my background threads was once busy creating a list of 2GB in silence as somebody had not cleared it. One thing to keep in mind is to periodically write down the memory usage or I would have pulled my hair out.
 
I am not sure that I would jump to refactoring. In the vast majority of cases, individuals think that their code is fine and adds more heap. IMO, profiling should be done first or you will be shooting in the dark. It may turn out that one of the methods is generating 10x the number of objects it is not supposed to. Fix it and your application would be running like a dream.
 
It can even be combination: increase -Xmx to prevent crashes in the meantime, profile to find the leaks and refactor the really ugly code. In addition, it is worth remembering GC tuning not all default collector is the best choice to suit your workload. I tend to watch jstat to know whether I am being killed by GC pauses.
 
Back
Top