How to deal with the 'java.lang.OutOfMemoryError: Java heap space' error?

Abdul D.
—The Problem
I don’t know how to deal with the java.lang.OutOfMemoryError: Java heap space error in Java.
The Solution
The java.lang.OutOfMemoryError: Java heap space error occurs when a Java virtual machine (JVM) runs out of memory to allocate new objects.
There are multiple ways to ensure the memory allocated to your JVM is sufficient for the requirements of an application, including the following common solutions:
- Using
-Xmsand-Xmxto increase the heap size - Using a profiling tool to analyze memory usage
- Using
-XX:+HeapDumpOnOutOfMemoryErrorto generate a heap dump - Tuning the garbage collector
Increase Heap Size
You can increase the heap size allocated to the JVM by using the -Xms and -Xmx options:
java -Xms512m -Xmx1024m YourApplication
- The
-Xmsparameter sets the initial heap size (for example,512mfor 512 MB). - The
-Xmxparameter sets the maximum heap size (for example,1024mfor 1 GB).
Analyze Memory Usage
You can use a profiling tool like VisualVM or YourKit to monitor memory usage and identify memory leaks or excessive memory consumption. This helps you identify which part of your code uses the most memory.
Use -XX:+HeapDumpOnOutOfMemoryError
-XX:+HeapDumpOnOutOfMemoryErrorYou can use the -XX:+HeapDumpOnOutOfMemoryError flag to generate a heap dump when the error occurs. You can then analyze the heap dump to find the root cause of the problem:
java -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError YourApplication
Garbage Collection Tuning
Tuning the garbage collector sometimes helps resolve memory issues. Experiment with different garbage collection algorithms (such as G1GC) and JVM options (like -XX:+UseG1GC) to see whether you can improve the JVM memory management.
Example
Suppose you have an application that reads a large file into memory all at once:
import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class Main { public static void main(String[] args) { try { byte[] data = Files.readAllBytes(Paths.get("largefile.txt")); System.out.println("File size: " + data.length); } catch (IOException e) { e.printStackTrace(); } } }
The code above will throw an OutOfMemoryError error if the file being read in is too large
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.base/java.util.Arrays.copyOf(Arrays.java:3745) at java.base/java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118) at java.base/java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93) at java.base/java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153) at java.base/java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:160) at java.base/java.nio.file.Files.read(Files.java:3273) at java.base/java.nio.file.Files.readAllBytes(Files.java:3326) at Main.main(Main.java:8)
This approach can easily lead to an OutOfMemoryError if the file is too large. To solve this, you could read the file in smaller chunks:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new FileReader("largefile.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }
- Sentry BlogException Handling in Java (with Real Examples)
- Syntax.fmListen to the Syntax Podcast
- Listen to the Syntax Podcast
![Syntax.fm logo]()
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODES
Considered “not bad” by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
