Inputs, outputs and UP-TO-DATE
The line that makes Gradle fast is the one it prints instead of doing the work: UP-TO-DATE. A task declares what it reads and what it writes, and Gradle compares both with the last run. When nothing changed the task is skipped; when the outputs are gone but the build cache still holds the result, the task comes back FROM-CACHE. This lesson shows all four outcomes on one compile task.
A project with a cache of its own
The build cache of this image lives in the user’s home and is shared by every project, so a page that wants a predictable first run points it at a folder inside the project. That is one block in the settings file:
settings.gradle
rootProject.name = 'shop'
buildCache {
local {
directory = new File(rootDir, 'build-cache')
}
}
build.gradle
plugins {
id 'java'
}
src/main/java/com/example/Counter.java
package com.example;
public final class Counter {
public static int next(int value) {
return value + 1;
}
}
The first build
gradle compileJava --build-cache --console=plain --offline --no-daemon
> Task :compileJava
BUILD SUCCESSFUL in 14s
1 actionable task: 1 executed
The second build: UP-TO-DATE
The same command again, with nothing changed. The task is not skipped because Gradle remembers running it: it is skipped because the hash of the inputs and the hash of the outputs are the same as the ones it stored.
gradle compileJava --build-cache --console=plain --offline --no-daemon
> Task :compileJava UP-TO-DATE
BUILD SUCCESSFUL in 11s
1 actionable task: 1 up-to-date
After clean: FROM-CACHE
Deleting build/ removes the outputs, so the up-to-date check fails. The build cache still holds the result of the same inputs, and the task takes it from there instead of compiling:
rm -rf build
gradle compileJava --build-cache --console=plain --offline --no-daemon
> Task :compileJava FROM-CACHE
BUILD SUCCESSFUL in 11s
1 actionable task: 1 from cache
The last line of the run says 1 actionable task: 1 from cache, and the class files are back in build/classes without a call to javac.
--rerun
Sometimes the check is right and the result is not, for example when a task read a file it did not declare. --rerun runs that one task again and ignores both the up-to-date check and the cache:
gradle compileJava --build-cache --rerun --console=plain --offline --no-daemon
> Task :compileJava
BUILD SUCCESSFUL in 12s
1 actionable task: 1 executed
Related
- Build and configuration caching: the two caches together, and the settings that turn them on.
- Write a task: the Copy type whose inputs and outputs this lesson relies on.
- mvn compile: how the other tool avoids the second compile, with Nothing to compile.
Article author: Arthur Isaev