All posts

Fix MemoryError in Spring Boot

Resolve OutOfMemoryError in Spring Boot applications, covering heap tuning, metaspace limits, and thread stack configuration.

Spring Boot OutOfMemoryError

Spring Boot applications throw java.lang.OutOfMemoryError with different messages depending on which memory area is exhausted. Each requires a different fix.

Java Heap Space

The most common OOM. The heap is full of live objects:

# Increase heap
java -Xmx1g -Xms512m -jar app.jar

But increasing heap is a band-aid. Find the leak:

# application.yml — enable heap dump on OOM
JAVA_OPTS: >-
  -XX:+HeapDumpOnOutOfMemoryError
  -XX:HeapDumpPath=/tmp/heapdump.hprof

Metaspace

OutOfMemoryError: Metaspace means too many classes are loaded, often from reflection-heavy libraries:

java -XX:MaxMetaspaceSize=256m -jar app.jar

Thread Stack

Too many threads exhaust native memory:

# Reduce thread stack size (default 1MB)
java -Xss512k -jar app.jar

Also configure Tomcat's thread pool:

server:
  tomcat:
    threads:
      max: 100  # Down from default 200

Container-Aware JVM Settings

ENV JAVA_OPTS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0 -XX:+HeapDumpOnOutOfMemoryError"
CMD java $JAVA_OPTS -jar app.jar

Connection Pool Sizing

spring:
  datasource:
    hikari:
      maximum-pool-size: 10
      minimum-idle: 5

Each connection uses memory for buffers and result sets.

Bugsly captures OutOfMemoryError events with the specific memory area, thread dump, and recent request context, dramatically reducing investigation time.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free