Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Build Scripts: Groovy and Kotlin DSL

Lazy Configuration: Providers, Properties and Task Avoidance

Understand Gradle's lazy configuration: Provider and Property types, map and flatMap, task configuration avoidance with register, and why it speeds up large builds.

Gradle evaluates your whole build script during the configuration phase, before any task runs. If every script computed every value on the spot, big builds would spend most of their time configuring things nobody needs. Lazy configuration solves this: instead of computing a value now, you describe how to compute it later. The building blocks are Provider<T>, Property<T> and task configuration avoidance (tasks.register). This lesson explains each and shows a runnable Kotlin stand-in of a provider.

The Gradle code is read-only. The stand-ins are plain Kotlin and Java, not Gradle.

The problem: values that are not ready yet

Recall the build lifecycle: at configuration time some values do not exist yet. The path of a file a task will produce, a version read from a property, the result of another task. If you copy such a value eagerly, you copy a stale or missing one. A provider is a handle that says "ask me later".

Provider and Property

  • Provider<T>: a read-only value that is computed on demand with get().
  • Property<T>: a provider you can also set: property.set("x") or property = "x".
Kotlin
val greeting = objects.property<String>()          // empty
greeting = "hello"                                 // set a value
val shout: Provider<String> = greeting.map { it.uppercase() }   // derived, still lazy

greeting = "hi"                                    // change it later
println(shout.get())                               // HI, computed now

Useful operations:

Operation Meaning
get() the value; fails if absent
getOrElse(x) / orElse(x) fallback when absent
orNull null when absent
map { } transform the value lazily
flatMap { } transform into another provider
zip(other) { a, b -> } combine two providers
isPresent whether a value exists

Providers also carry task dependencies. If a property's value comes from another task's output, Gradle knows to run that task first. This is why wiring outputs (outputFile = otherTask.flatMap { it.outputFile }) is better than dependsOn.

Collections have their own types: ListProperty<T>, SetProperty<T>, MapProperty<K, V>, and files use RegularFileProperty and DirectoryProperty.

Where providers come from

Kotlin
providers.gradleProperty("featureFlag")           // from gradle.properties or -P
providers.environmentVariable("CI")               // from the environment
providers.systemProperty("user.name")             // JVM system property
providers.provider { computeExpensiveValue() }    // custom lazy value
layout.buildDirectory.file("report.txt")          // lazy file location
tasks.named<Jar>("jar").flatMap { it.archiveFile }   // a task's output as a provider

Each is lazy: it is read when get() is called, usually during execution.

Stand-in: a tiny Provider in Kotlin

This is not Gradle's implementation, but it behaves the same for the basics. Run it and watch when the lambdas execute.

Kotlin Stand-in: lazy providers with map and orElse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The eager copy is frozen at 2.0.0, while the lazy provider follows the property to 3.0.0. That difference is the point of the whole API.

Task configuration avoidance

Gradle has two ways to create a task:

Kotlin
tasks.create("slow") { /* configured immediately, always */ }
tasks.register("fast") { /* configured only if something uses it */ }

register returns a TaskProvider. Gradle creates and configures the task only when it is needed: when it is in the requested task graph, or when another piece of code calls get(). In a build with hundreds of tasks per project and dozens of projects, this saves seconds on every run.

The matching lookup and configuration APIs are lazy too:

Kotlin
tasks.named("test") { ... }                       // configures only if/when test is created
tasks.withType<JavaCompile>().configureEach { ... }   // applies to each task as it is created

Avoid the eager ones: tasks.getByName, tasks.all { }, tasks.findByName, .get() inside configuration, and tasks.create.

Stand-in: counting what gets configured

The Java stand-in counts how many tasks get configured with eager creation versus lazy registration when only one task is requested.

Java Stand-in: eager create vs lazy register

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Rules of thumb

  1. Use Property/Provider for task and extension fields instead of plain var.
  2. Pass providers around; call get() only inside task actions or inside a map.
  3. Use register, named, and configureEach.
  4. Read configuration values (properties, environment) through providers.* so they are tracked.
  5. Avoid reading files or running processes at configuration time. If you must, use providers.fileContents(...) or providers.exec { }, which are lazy and cache-aware.

Following these rules also makes your build compatible with the configuration cache, which stores the result of the configuration phase and skips it entirely on the next run; see the performance chapter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a Provider<T> in Gradle?

    Providers defer evaluation, so values that are not ready at configuration time can still be wired.
  2. 2. Which call creates a task only when it is needed?

    register returns a TaskProvider and defers creation and configuration.
  3. 3. How is a Property different from a Provider?

    Property<T> extends Provider<T> and adds set(...).
  4. 4. Why is wiring a task's output provider into another task better than only dependsOn?

    Output providers tell Gradle both where the value comes from and which task produces it.

Summary

  • Lazy configuration defers computation until a value is really needed.
  • Provider<T> is a read-only lazy value; Property<T> is a settable provider; use map, flatMap, orElse, zip.
  • Providers carry task dependencies when they come from task outputs.
  • tasks.register, named and configureEach avoid configuring unused tasks.
  • Read properties, environment and files through providers.* for correctness and caching.

Next: Declaring Dependencies and Configurations