Lazy Configuration: register & Providers
The configuration phase runs on every build, even gradle help. A build with 300 projects and 40 tasks each spends seconds configuring before anything happens, unless configuration is lazy: tasks are only created and configured when the graph actually needs them, and values are only computed when a task runs. Two APIs make that possible: tasks.register and the Provider/Property types.
register vs create
tasks.create("x") { … } creates and configures the task immediately. tasks.register("x") { … } only records how to create it; Gradle runs the block if the task ends up in the graph (or someone asks for it). The session prints a line whenever a configuration block runs:
mkdir lazy && cd lazy
echo 'rootProject.name = "lazy"' > settings.gradle.kts
cat > build.gradle.kts <<'KTS'
tasks.create("eager") {
println("configuring eager")
doLast { println("running eager") }
}
tasks.register("lazy") {
println("configuring lazy")
doLast { println("running lazy") }
}
KTS
echo '$ gradle -q help'; gradle -q help | grep configuring
echo '$ gradle -q lazy'; gradle -q lazy
echo '$ gradle -q eager'; gradle -q eager$ gradle -q help
configuring eager
$ gradle -q lazy
configuring eager
configuring lazy
running lazy
$ gradle -q eager
configuring eager
running eager
eager was configured for help, a build that never runs it; lazy only when requested. With one task that costs nothing. With a plugin that creates twenty tasks in each of 300 projects, it's 6000 task objects per build. The same rule applies to collections: tasks.withType<Test>().configureEach { … } is lazy, tasks.withType<Test> { … } and tasks.getByName("test") are not, and tasks.named("test") returns a lazy handle.
Note:
tasks.createstill works in Gradle 9 but is on its way out; new code should never use it.
Properties and providers
A Provider<T> is a value that may not be known yet; a Property<T> is a provider you can also set. Tasks declare their inputs and outputs as properties, and you connect them instead of copying values:
task.input.set(otherTask.flatMap { it.output })(or=in the Kotlin DSL) links one task's output to another's input, and Gradle infers the task dependency from it: nodependsOn..map { }derives a value lazily; nothing is computed until a task calls.get().providers.gradleProperty("x"),providers.environmentVariable("X"),layout.buildDirectory.file("…")are lazy sources.
A custom task class with annotated inputs and outputs, and two tasks wired together by their properties:
mkdir wired && cd wired
echo 'rootProject.name = "wired"' > settings.gradle.kts
cat > build.gradle.kts <<'KTS'
abstract class WriteVersion : DefaultTask() {
@get:Input abstract val version: Property<String>
@get:OutputFile abstract val outputFile: RegularFileProperty
@TaskAction
fun write() {
outputFile.get().asFile.writeText("version=${version.get()}\n")
println("wrote ${outputFile.get().asFile.name}")
}
}
abstract class ShowFile : DefaultTask() {
@get:InputFile abstract val inputFile: RegularFileProperty
@TaskAction
fun show() = print("read: " + inputFile.get().asFile.readText())
}
val writeVersion = tasks.register<WriteVersion>("writeVersion") {
version = providers.gradleProperty("appVersion").orElse("0.0.1-dev")
outputFile = layout.buildDirectory.file("version.properties")
}
tasks.register<ShowFile>("showVersion") {
inputFile = writeVersion.flatMap { it.outputFile } // no dependsOn needed
}
KTS
gradle -q showVersion
gradle -q showVersion -PappVersion=2.0.0
gradle showVersion -PappVersion=2.0.0 | grep '^> Task'wrote version.properties
read: version=0.0.1-dev
wrote version.properties
read: version=2.0.0
> Task :writeVersion UP-TO-DATE
> Task :showVersion
showVersionpulled inwriteVersionbecause its input iswriteVersion's output.-PappVersionreached the task through a provider chain set up long before the property had a value.- The third run printed
UP-TO-DATEforwriteVersion: Gradle compared the declared input (version) and output (version.properties) with the previous run. Annotated properties are what make incremental builds and the build cache possible. A task without declared outputs is never up to date.
A model: providers are recipes
class Provider:
def __init__(self, compute, name):
self.compute, self.name = compute, name
def map(self, f, name):
return Provider(lambda: f(self.get()), name)
def get(self):
print(f" computing {self.name}")
return self.compute()
props = {} # gradle properties, filled later
version = Provider(lambda: props.get("appVersion", "0.0.1-dev"), "version")
banner = version.map(lambda v: f"MyApp {v}", "banner")
print("configured (nothing computed yet)")
props["appVersion"] = "2.0.0" # e.g. set by -PappVersion
print("task runs:", banner.get())configured (nothing computed yet)
computing banner
computing version
task runs: MyApp 2.0.0
Nothing was computed during "configuration", and the value seen at execution time is the latest one. An eager val banner = "MyApp " + version would have frozen 0.0.1-dev.
Test yourself
What is the difference between tasks.register and tasks.create?
- None
- register defers creating/configuring the task until it is needed; create does it immediately
- create is lazy, register is eager
- register only works in buildSrc
Task B's input is set to taskA.flatMap { it.outputFile }. What else must you add so A runs before B?
- B.dependsOn(A)
- Nothing: Gradle infers the dependency from the provider
- A.finalizedBy(B)
- B.mustRunAfter(A)
Which call configures all Test tasks lazily?
- tasks.withType<Test> { }
- tasks.withType<Test>().configureEach { }
- tasks.getByName("test")
- allprojects { }