Skip to content
Latchkey

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/caches and ~/.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 build

Gotchas

  • setup-gradle saves a cache only from the default branch by default, which avoids cross-branch pollution.
  • Run with --no-daemon in CI; a leftover daemon can hold the cache directory and cause flaky writes.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →