Skip to content
Latchkey

Spring Boot "java.lang.OutOfMemoryError" during tests in CI

The test JVM ran out of heap. In Spring Boot suites this is often caused by many distinct @SpringBootTest contexts (or @DirtiesContext) accumulating in memory, plus a runner heap smaller than your laptop.

What this error means

The test task fails with "java.lang.OutOfMemoryError: Java heap space" or "Metaspace", often after a batch of integration tests, and passes locally with more RAM.

JVM
java.lang.OutOfMemoryError: Java heap space
	at org.springframework.context.support.AbstractApplicationContext.refresh(...)

Common causes

Too many distinct application contexts

Each unique test configuration builds a new context; without caching they pile up and exhaust the heap.

A smaller heap on the runner

The CI runner has less memory than a developer machine, so a suite that fits locally overflows in CI.

How to fix it

Raise and cap the test JVM heap

Give the test task a heap that fits the runner and fails fast on leaks.

build.gradle.kts
tasks.test {
  maxHeapSize = "2g"
  jvmArgs("-XX:+HeapDumpOnOutOfMemoryError")
}

Reduce context churn

  1. Share one context across tests by keeping test configuration identical.
  2. Remove unnecessary @DirtiesContext so contexts are cached and reused.
  3. Prefer slices (@WebMvcTest/@DataJpaTest) over full contexts.

How to prevent it

  • Keep test configurations uniform so Spring caches one context.
  • Use @DirtiesContext only when a test truly mutates the context.
  • Set an explicit test heap sized for the runner.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →