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 Test Executor 1 ...
com.example.BigDataTest > loadsLargeFixture FAILED
java.lang.OutOfMemoryError: Java heap space
> Task :app:test FAILEDCommon 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.
tasks.test {
maxHeapSize = "2g"
jvmArgs("-XX:MaxMetaspaceSize=512m")
// optional: bound parallel workers so they fit in RAM
maxParallelForks = 2
}Reduce per-worker footprint
- Lower
maxParallelForksso concurrent test JVMs fit the runner RAM. - Use
forkEveryto recycle the worker periodically and release retained memory. - 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
maxParallelForksso forked test JVMs fit the runner RAM. - Free large resources between tests; use
forkEveryfor leak-prone suites.