Skip to content
Latchkey

Gradle Test Worker "OutOfMemoryError: Java heap space" - Fix in CI

Gradle runs tests in a forked "test worker" JVM with its own heap - independent of org.gradle.jvmargs. This OOM is in that worker: its -Xmx is too small for the tests (large fixtures, big datasets, leaks across tests).

What this error means

The test task fails with java.lang.OutOfMemoryError: Java heap space attributed to the Gradle Test Executor / a test worker thread, not the Gradle daemon. Raising org.gradle.jvmargs alone does not help - the worker has its own heap.

gradle output
Gradle Test Executor 1 ...
com.example.BigDataTest > loadsLargeFixture FAILED
    java.lang.OutOfMemoryError: Java heap space
> Task :app:test FAILED

Common causes

Test worker -Xmx too small

The forked test JVM defaults to a modest heap. Tests that load large fixtures or datasets exhaust it. This heap is set on the test task, not via org.gradle.jvmargs.

Memory accumulating across tests

Static caches or undisposed resources retained across many tests in one worker push the heap over its ceiling, even if any single test is small.

How to fix it

Raise the test worker heap

Set maxHeapSize (and metaspace) on the test task - this targets the forked worker, not the daemon.

build.gradle.kts
tasks.test {
    maxHeapSize = "2g"
    jvmArgs("-XX:MaxMetaspaceSize=512m")
    // optional: bound parallel workers so they fit in RAM
    maxParallelForks = 2
}

Reduce per-worker footprint

  1. Lower maxParallelForks so concurrent test JVMs fit the runner RAM.
  2. Use forkEvery to recycle the worker periodically and release retained memory.
  3. Profile a heap dump (-XX:+HeapDumpOnOutOfMemoryError) if a leak is suspected.

How to prevent it

  • Set test { maxHeapSize } explicitly rather than relying on the default.
  • Bound maxParallelForks so forked test JVMs fit the runner RAM.
  • Free large resources between tests; use forkEvery for leak-prone suites.

Related guides

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