# Java: Fix OutOfMemoryError Java Heap Space Error

> Increase JVM heap size with -Xms and -Xmx, generate a heap dump with -XX:+HeapDumpOnOutOfMemoryError, or read large files in chunks to avoid OutOfMemoryError

**URL:** https://sentry.io/answers/how-to-deal-with-java-lang-outofmemoryerror-java-heap-space-error/

---

## 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 `-Xms` and `-Xmx` to increase the heap size
- Using a profiling tool to analyze memory usage
- Using `-XX:+HeapDumpOnOutOfMemoryError` to 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 `-Xms` parameter sets the initial heap size (for example, `512m` for 512 MB).
- The `-Xmx` parameter sets the maximum heap size (for example, `1024m` for 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`

You 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:

```java
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:

```java
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();
        }
    }
}
```

---

*Source: [sentry.io/answers/how-to-deal-with-java-lang-outofmemoryerror-java-heap-space-error/](https://sentry.io/answers/how-to-deal-with-java-lang-outofmemoryerror-java-heap-space-error/)*
