They say prevention is better than cure. This is especially true when it comes to system crashes in production, which can result in major disruptions to client services. And, of course, much finger-pointing and blame-shifting in the IT department.
This article looks at ways to avoid OutOfMemoryError. Java programmers often assume the garbage collector (GC) will take care of memory issues, and don’t spend enough time and thought on making sure systems will still work efficiently under production loads.
Memory issues, besides potentially crashing the system, can cause severe performance problems. The garbage collector uses more and more resources as memory runs low, and the operating system may begin paging heavily.
Good memory management is therefore essential for critical systems.
OutOfMemory Errors and the JVM Memory Model
Let’s first look at the JVM memory model, and see how different types of OutOfMemoryErrors relate to it.

Fig: JVM Memory Model
Briefly, JVM memory is divided into several pools:
- The Heap: Central storage area for all objects used by the application;
- Metaspace (Formerly PermGen): Class metadata, method byte code etc.;
- Threads: Stacks for each running thread;
- Code Cache: Compiled code for ‘hot’ program areas;
- Direct Buffers: Special buffer area for fast I/O;
- GC: Reserved for the garbage collector;
- JNI: Used by the Java Native Interface;
- Misc: Other JVM-reserved memory.
For more information, here’s a link to a video explaining the JVM Memory Model.
When you’re optimizing JVM memory, you need to take several of these pools into account. There are 9 types of OutOfMemory errors in Java.
The diagram below shows the 9 error messages you may encounter, and how they relate to the different memory pools.

Fig: 9 Types of OutOfMemoryErrors in Java, and Memory Areas They Relate to
Notice that the error in the top box does not relate to JVM memory: it’s thrown by the operating system when the device or container runs dangerously low on memory.
To optimize memory, it’s also important to understand how the garbage collector works. Monitoring garbage collection (GC) can give advance warning of any memory problems that may be developing.
Calculating Memory Requirements
When we’re planning an application, it’s important to be aware of how much memory it will actually need.
To help you estimate your requirements:
- Java Primitives: See Oracle’s documentation to see how much memory each data type occupies.
- Objects: This can be difficult to estimate, especially since objects can create other objects ad infinitum. This is especially true when you’re using third party libraries. “Shallow Heap” refers to the amount of memory the object itself occupies. “Retained Heap” refers to the memory occupied by the object and all its live children. There is also a small overhead for object headers. Two ways you may be able to get information about object sizes are:
- The OpenJDK JOL Library has a means of programmatically obtaining the size of an object;
- The HeapHero tool can be used in early testing to obtain exact figures for both shallow and retained heap memory.
- Images: These occupy a significant amount of RAM, depending on size, image quality etc. Here’s a handy Image Size Calculator.
- Videos: These are very memory-hungry. See this Video Size Calculator.
Avoid OutOfMemoryErrors: Java Program Planning
The two most common reasons for OutOfMemory errors are:
- Memory Leaks: where objects are not released in a timely manner;
- Not taking into account memory constraints at the planning stage.
Before we start coding, we should give thought to what we need: memory, threads, classes, buffers and native libraries. Why do we need them? How many do we need? How long do they need to be retained? Some objects may be needed throughout the lifespan of the program, while others are needed only for the duration of a single transaction.
To avoid memory leaks, objects should always be defined within the correct scope. If they’re only needed for the duration of a single method, they should be defined as local variables, ensuring they’re garbage collected when the method completes. Streams should always be closed after use; large objects such as buffers should be dereferenced by setting them to null when they’re no longer needed.
Remember to allow for an increase in traffic over time, and take into account the needs of third-party libraries.
Testing and Monitoring
For large applications especially, it’s worth including memory usage statistics in your test plan. Taking a heap dump allows us to see how much memory is actually being used, and by what objects. Analyzing the dump is time-consuming, so it’s a good idea to use a tool such as HeapHero to present the data in an interactive, visual form. HeapHero includes overall memory statistics, lists of objects in memory sorted from largest to smallest, and information about the classes held in the metaspace.
The image below shows HeapHero’s scrollable list of objects, along with shallow and retained heap size.

Fig: List of Objects in the Heap Produced By HeapHero
From each object, we can interactively search for parents and children, or view the object’s contents.
The same information can also be viewed in chart form, as shown below.

Fig: Largest Objects in Chart Form
Load testing is extremely important for preventing memory issues in production. With the aid of HeapHero, we can not only see whether memory is being used efficiently, but also gather important statistics that allow us to configure memory parameters correctly when the system goes live.
Another important aspect of load testing is ensuring the garbage collector is performing efficiently. It should be effectively clearing memory while not using excessive resources. GCeasy is an excellent tool for quickly analyzing GC logs to provide meaningful information.
Since application loads generally grow over time, it’s worth regularly monitoring memory usage and GC efficiency once the system is live. This allows us to pre-empt performance issues and OutOfMemory crashes. It’s not difficult to tune heap, metaspace and direct buffer sizes using JVM arguments. Garbage collection can also be tuned for better performance.
Avoiding OutOfMemory Errors:Tips and Techniques
Can you cut down your program’s memory usage? Here are a few tips that may help.
- Use pools to ensure resources can be reused. Buffers, database connectors and threads are examples where resource pools are often used successfully. The Java Executor Service simplifies the job of managing thread pools.
- Caching for high-speed searches improves performance – until memory runs short. Large caches can actually slow the system down if they’re causing the GC to become overactive. Consider using soft references for caching. As soon as memory runs short, soft references are automatically garbage collected, giving you the best of both options.
- String deduplication can be a big memory saver in programs that work heavily with strings.
- Take extra care when using objects that can grow indefinitely, such as ArrayLists, HashMaps and Vectors. It’s all too easy to allow these objects to reach very large sizes if they’re not carefully managed.
- Use streams rather than loading an entire file.
- Although SSD is still much slower than RAM, it is up to 1000 times faster than HDD. Consider, when holding large amounts of data in memory, whether the performance trade-off is still worth the memory required to do this.
- Make sure objects are dereferenced when they’re no longer needed.
Conclusion
To avoid OutOfMemoryError, Java programmers need to cultivate memory-awareness at all stages of a project’s life cycle. At the planning stage, give thought to the memory requirements of the different strategies you’re considering. When coding, make sure memory is not retained for longer than necessary.
Testing large systems should include heap dump analysis, to make sure memory is being used correctly. Load testing is essential, and it’s worth using tools such as HeapHero and GCEasy to analyze memory usage.
Finally, critical applications should be regularly monitored in production, to ensure increased loads won’t result in OutOfMemory crashes.

Share your Thoughts!