How to Cache Gradle in GitHub Actions
Use gradle/actions/setup-gradle for automatic dependency and build-cache reuse, or cache ~/.gradle/caches yourself.
The simplest path is the official gradle/actions/setup-gradle, which restores Gradle dependencies and the build cache and only writes from the default branch by default. For full control, cache ~/.gradle/caches and ~/.gradle/wrapper keyed on your build scripts.
Steps
- Prefer
gradle/actions/setup-gradle, which handles dependency and build-cache restore. - For a manual cache, cache
~/.gradle/cachesand~/.gradle/wrapper. - Key on
hashFiles('**/*.gradle*', '**/gradle-wrapper.properties').
Workflow
.github/workflows/ci.yml
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- run: ./gradlew buildGotchas
setup-gradlesaves a cache only from the default branch by default, which avoids cross-branch pollution.- Run with
--no-daemonin CI; a leftover daemon can hold the cache directory and cause flaky writes.
Related guides
How to Cache the Maven Repository in GitHub ActionsCache the local Maven repository (~/.m2/repository) in GitHub Actions keyed on the pom.xml files, so mvn buil…
How to Cache the Turborepo Computation Cache in GitHub ActionsCache the Turborepo (or Nx) local computation cache in GitHub Actions keyed on source and lockfile, so unchan…