How to Cache the .gradle Directory in GitHub Actions
A fresh runner re-downloads every Gradle dependency and wrapper distribution unless the Gradle home is cached.
The official gradle/actions/setup-gradle action caches ~/.gradle/caches and the wrapper for you; you can also cache it manually keyed on your build scripts.
Steps
- Set up the JDK with
actions/setup-java. - Add
gradle/actions/setup-gradleto enable dependency and configuration caching. - For a manual approach, cache
~/.gradle/cachesand~/.gradle/wrapper. - Key on
hashFilesof*.gradle*andgradle-wrapper.properties.
Workflow
.github/workflows/gradle.yml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v4
- run: ./gradlew build --build-cacheGotchas
- Pass
--build-cacheso Gradle actually reuses task outputs, not just downloaded jars. - Avoid caching
~/.gradlewholesale; daemon logs and locks bloat the cache. - Latchkey keeps the Gradle home warm across jobs so JVM builds start fast and retry transient failures.
Related guides
How to Cache Maven .m2 in GitHub ActionsCache the Maven local repository (~/.m2/repository) in GitHub Actions, keyed on pom.xml, so Java builds skip…
How to Cache the Rust target Directory in GitHub ActionsCache Cargo registry, git deps, and the target directory in GitHub Actions, keyed on Cargo.lock, so Rust CI r…