Build and configuration caching

A Gradle build has two parts: the configuration, which reads the scripts and builds the task graph, and the execution, which runs the tasks. Each part has a cache of its own. The build cache answers "may I skip this task", the configuration cache answers "may I skip the scripts", and a build that turns both on is fast on the second run of the same command.

Two caches, two questions

build cache configuration cache
what it stores the outputs of a task, keyed by its inputs the task graph of one command, with the state of the scripts
the line it prints FROM-CACHE on a task Reusing configuration cache.
when it helps a clean build of the same sources, on any machine with the same cache the second and every later run of the same command
the switch org.gradle.caching=true or --build-cache org.gradle.configuration-cache=true or --configuration-cache

The first run

settings.gradle

rootProject.name = 'shop'

build.gradle

plugins { id 'java' }

src/main/java/com/example/App.java

package com.example; public final class App { public static void main(String[] args) { System.out.println("shop"); } }

gradle build --configuration-cache --console=plain --offline --no-daemon 2>&1 | grep -E "onfiguration cache|BUILD"

BUILD SUCCESSFUL in 22s
Configuration cache entry stored.

The second run

The same command again, with nothing changed. Gradle reads the stored graph instead of the scripts, and every task is already up to date:

gradle build --configuration-cache --console=plain --offline --no-daemon 2>&1 | grep -E "onfiguration cache|BUILD"

Reusing configuration cache.
BUILD SUCCESSFUL in 17s
Configuration cache entry reused.

The task lines are left out above, and the filter keeps the two lines that matter. Gradle does not promise an order between two tasks that do not depend on each other, so a page that lists every task of a build can differ from one run to the next in exactly those lines; the cache lines do not.

A change to a build script, to a version in the catalog or to a property invalidates the entry, and the next run stores a new one. That is the price of the cache: a build script must not read the clock, the environment or a file that Gradle does not know about, and Gradle fails the build with the reason when it does.

The two switches

gradle.properties

# Skip the configuration of a command that ran before. org.gradle.configuration-cache=true # Take the outputs of a task from the cache instead of running it. org.gradle.caching=true

Both properties belong in the gradle.properties of the project, so every developer and every CI job gets them without a flag. The configuration cache of Gradle 9 is on by default for a project gradle init writes, and it is off for a build script that has not been checked against it.

Related

Article author: Arthur Isaev