CI Gradle build fails with 'duplicate classes' intermittently in Docker-in-Docker runners due to shared Gradle cache corruption
Environment
Self-hosted GitHub Actions runner using Docker-in-Docker executor, OpenJDK 11, Gradle 7.5, builds run in containers spawned from a shared runner image; host mounts /home/gradle/.gradle as a persistent volume across jobs.
Symptoms
Random CI builds fail with Java compile/link errors reporting duplicate classes (same FQCN found in multiple jars) during Gradle compileKotlin/Java. Failures are non-deterministic and often succeed after re-run.
Observations
Cleaning project (gradle clean) sometimes doesn't help. Deleting the runner's shared ~/.gradle cache directory and rerunning fixes builds for several job executions. Multiple concurrent jobs share the same host-mounted Gradle cache volume; logs show simultaneous downloads and cache writes before a failure.
Already attempted
Clean build, removed ~/.gradle cache on host (fixes temporarily), switched to ephemeral container cache (works but increases network downloads), tried locking cache via external script (partial improvement).
Question
What's causing intermittent duplicate-class build failures in CI when using a shared Gradle cache across concurrent Docker-in-Docker jobs, and how can I fix it reliably without removing cache persistence entirely?
Verified community troubleshooting
The intermittent 'duplicate classes' in D-in-D CI almost always means your shared Gradle cache is being written concurrently by multiple builds and getting corrupted. Make each job use an isolated cache: set GRADLE_USER_HOME=$GITHUB_WORKSPACE/.gradle (or another per-job path) and disable the daemon in CI (org.gradle.daemon=false or pass -Dorg.gradle.daemon=false). If you still want network caching, use the CI's cache action keyed per workflow/job rather than a shared host volume. Verify by running parallel jobs; if errors vanish you're good. Rollback: revert GRADLE_USER_HOME and daemon settings.
Incident analysis
Most likely causes
Summary
Suggested Fixes
Continue troubleshooting
Related troubles
Matched from the title, description and tags
- Software41% match
Self-hosted GitHub Actions runners produce incomplete multi-stage Docker images after kernel update (overlay2: missing build artifacts)
Open0 answers - Cloud Computing30% match
Self-hosted GitHub Actions runner cannot access /var/run/docker.sock when launched as systemd service
Solved1 answer - Cloud Computing28% match
GitHub Actions Docker build times out pushing large build context because .cache and node_modules are included
Solved1 answer - Cloud Computing23% match
GitLab Runner (podman) fails writing CI cache to host-mounted directory: permission denied on Ubuntu 22.04
Solved1 answer