// Copyright (C) 2024 Gradle, Inc.
//
// Licensed under the Creative Commons Attribution-Noncommercial-ShareAlike 4.0 International License.;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

:gradle-issues: https://github.com/gradle/gradle/issues/

[[config_cache]]
= Configuration Cache
:keywords: configuration-cache, no-configuration-cache, org.gradle.configuration-cache, org.gradle.configuration-cache.problems, org.gradle.configuration-cache.max-problems, org.gradle.configuration-cache.parallel, STABLE_CONFIGURATION_CACHE,

// Run tests for snippets included in this chapter with:
// ./gradlew :docs:docsTest --tests="ExemplarExternalSamplesFunctionalTest.snippet-configuration-cache-*"
// ./gradlew :docs:docsTest --tests="ExemplarExternalSamplesFunctionalTest.snippet-value-providers-*"

[[config_cache:intro]]
The Configuration Cache improves build performance by caching the result of the <<build_lifecycle#build_lifecycle,configuration phase>> and reusing it for subsequent builds.

When enabled, the Configuration Cache allows Gradle to skip the configuration phase entirely if nothing that affects the build configuration (such as build scripts) has changed.
Additionally, Gradle applies performance optimizations to task execution.

The Configuration Cache is similar to the <<build_cache#build_cache,Build Cache>>, but they store different types of data:

- *Build Cache*: Stores outputs and intermediate files of the build (e.g., task outputs, artifact transform outputs).
- *Configuration Cache*: Stores the build configuration for a particular set of tasks, capturing the output of the configuration phase.

image::configuration-cache-2.png[]

[IMPORTANT]
====
This feature is _not enabled by default_ and has the following limitations:

- It does not yet support all <<configuration_cache#config_cache:plugins:core, Core Gradle Plugins>> and <<configuration_cache#config_cache:not_yet_implemented, features>>. Full support is in progress.
- Your build and its plugins may require modifications to meet the <<configuration_cache#config_cache:requirements, Configuration Cache requirements>>.
- IDE imports and syncs do not yet use the Configuration Cache.
====

[[config_cache:intro:how_does_it_work]]
== How Configuration Caching Works

When the Configuration Cache is enabled and you run Gradle for a particular set of tasks, such as `gradlew check`, Gradle checks for a Configuration Cache entry.
If an entry exists, Gradle uses it to skip the configuration phase.

A cache entry contains:

- The set of tasks to run
- Their configuration details
- Dependency information

=== First-Time Execution

image::configuration-cache-1.png[]

The first time you run a set of tasks, there is no cache entry.
Gradle performs the configuration phase as usual:

1. Run init scripts.
2. Run the settings script, applying any requested settings plugins.
3. Configure and build the `buildSrc` project, if present.
4. Run build scripts, applying any requested project plugins. If plugins come from included builds, Gradle builds them first.
5. Calculate the task graph, executing deferred configuration actions.

Gradle then stores a snapshot of the task graph in the Configuration Cache for future use.
After this, Gradle loads the task graph from the cache and proceeds with task execution.

=== Subsequent Runs

image::configuration-cache-3.png[]

On subsequent executions of the same tasks (e.g., `gradlew check` again), Gradle:

- Skips the configuration phase entirely.
- Loads the task graph from the Configuration Cache instead.

Before using the cache, Gradle verifies that no build configuration inputs have changed.
If any input has changed, Gradle reruns the configuration phase and updates the cache.

=== Build Configuration Inputs

The following elements determine whether a Configuration Cache entry is valid:

1. Gradle environment
** `GRADLE_USER_HOME`
** Gradle Daemon JVM
2. Init scripts
3. `buildSrc` and included build logic build contents (build scripts, sources, and intermediate build outputs)
4. Build and Settings scripts, including included scripts (`apply from: foo.gradle`)
5. Gradle configuration files (Version Catalogs, dependency verification files, dependency lock files, `gradle.properties` files)
6. Contents of files read at configuration time
7. File system state checked at configuration time (file presence, directory contents, etc.)
8. Custom `ValueSource` values obtained at configuration time (this also includes built-in providers, like `providers.exec` and `providers.fileContents`).
9. System properties used during the configuration phase
10. Environment variables used during the configuration phase

=== Serialization

Gradle uses an optimized serialization mechanism to store Configuration Cache entries.
It automatically serializes object graphs containing simple state or supported types.

While Configuration Cache serialization doesn't rely on Java Serialization, it understands <<configuration_cache#config_cache:not_yet_implemented:java_serialization, some of its features>>.
This can be used to customize serialization behavior, but incurs performance penalty and should be avoided.

[[config_cache:intro:performance_improvements]]
=== Performance Improvements

Beyond skipping the configuration phase, the Configuration Cache enhances performance in the following ways:

- *Parallel Task Execution*: All tasks run in parallel by default, subject to dependency constraints.
- *Cached Dependency Resolution*: Dependency resolution results are stored and reused.
- *Optimized Memory Usage*: After writing the task graph to the cache, Gradle discards configuration and dependency resolution state from memory, lowering peak heap usage.

[[config_cache:in_action]]
image::configuration-cache/running-help.gif[]

[[config_cache:usage]]
== Trying out the Configuration Cache

It is recommended to get started with the simplest task invocation possible.

Running `help` with the Configuration Cache enabled is a good first step:

[source,text]
----
❯ ./gradlew --configuration-cache help
include::{snippetsPath}/configurationCache/noProblem/tests/store.out[]
...
BUILD SUCCESSFUL in 4s
1 actionable task: 1 executed
Configuration cache entry stored.
----

Running this for the first time, the configuration phase executes, calculating the task graph.

Then, run the same command again.

This reuses the cached configuration:

[source,text]
----
❯ ./gradlew --configuration-cache help
include::{snippetsPath}/configurationCache/noProblem/tests/load.out[]
...
BUILD SUCCESSFUL in 500ms
1 actionable task: 1 executed
Configuration cache entry reused.
----

If it succeeds on your build, congratulations, you can now try with more useful tasks.
You should target your development loop.
A good example is running tests after making incremental changes.

If any problem is found caching or reusing the configuration, an HTML report is generated to help you diagnose and fix the issues.
The report also shows detected build configuration inputs like system properties, environment variables and value suppliers read during the configuration phase.

See the <<configuration_cache#config_cache:troubleshooting>> section below for more information.

[[config_cache:usage:enable]]
== Enabling the Configuration Cache

By default, Gradle does not use the Configuration Cache.

To enable it at build time, use the `configuration-cache` flag:

[source,text]
----
❯ ./gradlew --configuration-cache
----

To enable the cache persistently, set the `org.gradle.configuration-cache` property in `gradle.properties`:

[source,properties]
----
org.gradle.configuration-cache=true
----

If enabled in `gradle.properties`, you can override it and disable the cache at build time using the `no-configuration-cache` flag:

[source,text]
----
❯ ./gradlew --no-configuration-cache
----

[[config_cache:usage:ignore_problems]]
=== Ignoring Configuration Cache Problems

By default, Gradle fails the build if Configuration Cache problems occur.
However, when gradually updating plugins or build logic to support the Configuration Cache, it can be useful to temporarily turn problems into warnings.

NOTE: This does not guarantee that the build will succeed.

To change this behavior at build time, use the following flag:

[source,text]
----
❯ ./gradlew --configuration-cache-problems=warn
----

Alternatively, configure it in `gradle.properties`:

[source,properties]
----
org.gradle.configuration-cache.problems=warn
----

[[config_cache:usage:max_problems]]
=== Allowing a Maximum Number of Problems

When Configuration Cache problems are treated as warnings, Gradle will fail the build if `512` problems are found by default.

You can adjust this limit by specifying the maximum number of allowed problems on the command line:

[source,text]
----
❯ ./gradlew -Dorg.gradle.configuration-cache.max-problems=5
----

Or configure it in a `gradle.properties` file:

[source,properties]
----
org.gradle.configuration-cache.max-problems=5
----

[[config_cache:usage:parallel]]
=== Enabling Parallel Configuration Caching

By default, Configuration Cache storing and loading are sequential.
Enabling parallel storing and loading can improve performance, but not all builds are compatible with it.

To enable parallel configuration caching at build time, use:

[source,text]
----
❯ ./gradlew -Dorg.gradle.configuration-cache.parallel=true
----

Or persistently in a `gradle.properties` file:

[source,properties]
----
org.gradle.configuration-cache.parallel=true
----

[WARNING]
====
The parallel configuration caching feature is _incubating_, and some builds may not work correctly.
A common symptom of incompatibility is `ConcurrentModificationException` errors during the <<build_lifecycle#sec:configuration,configuration phase>>.
However, this feature is expected to work well for <<multi_project_configuration_and_execution#sec:decoupled_projects,decoupled>> multi-project builds.
====

[[config_cache:usage:invalidate]]
== Invalidating the Configuration Cache

The Configuration Cache is automatically invalidated when inputs to the configuration phase change.
However, some inputs are not yet tracked, meaning you may need to manually invalidate the cache when untracked inputs change.
This is more likely if you have <<configuration_cache#config_cache:usage:ignore_problems,ignored problems>>.

See the <<configuration_cache#config_cache:requirements>> and <<configuration_cache#config_cache:not_yet_implemented>> sections for more details.

The Configuration Cache state is stored in a `.gradle/configuration-cache` directory in the root of your Gradle build.

To manually invalidate the cache, delete this directory:

[source,text]
----
❯ rm -rf .gradle/configuration-cache
----

Gradle periodically checks (at most every 24 hours) whether cached entries are still in use.
Entries that have not been used for 7 days are automatically deleted.

[[config_cache:stable]]
== Preparing for Configuration Cache Stability

To ensure a smooth transition as Gradle stabilizes configuration caching, a strict mode has been implemented behind a feature flag.

You can enable the feature flag in your build as follows:

====
include::sample[dir="snippets/configurationCache/stableFeatureFlag/kotlin",files="settings.gradle.kts[]"]
include::sample[dir="snippets/configurationCache/stableFeatureFlag/groovy",files="settings.gradle[]"]
====

The `STABLE_CONFIGURATION_CACHE` feature flag enforces stricter validation and introduces the following behavior:

Undeclared Shared Build Service Usage::
Tasks using a <<build_services#build_services, shared Build Service>> without explicitly declaring the requirement via the `Task.usesService` method will trigger a deprecation warning.

Additionally, when the Configuration Cache is not enabled but this feature flag is present, deprecations for the following <<config_cache:requirements, Configuration Cache requirements>> will be enforced:

- <<config_cache:requirements:build_listeners, Registering build listeners>>
- <<config_cache:requirements:task_extensions, Using task extensions and conventions at execution time>>

It is recommended to enable this flag as soon as possible to prepare for its eventual default enforcement.

[[config_cache:ide]]
== IDE Support

If you enable and configure the Configuration Cache in your `gradle.properties` file, it will be automatically enabled when your IDE delegates builds to Gradle.
No additional setup is required.

Because `gradle.properties` is typically checked into source control, enabling the Configuration Cache this way will apply to your entire team.
If you prefer to enable it only for your local environment, you can configure it directly in your IDE instead.

NOTE: Syncing a project in an IDE does not benefit from the Configuration Cache. Only running tasks through the IDE will leverage the cache.

[[config_cache:ide:intellij]]
=== IntelliJ based IDEs

In IntelliJ IDEA or Android Studio this can be done in two ways, either globally or per run configuration.

To enable it for the whole build, go to `Run > Edit configurations...`.
This will open the IntelliJ IDEA or Android Studio dialog to configure Run/Debug configurations.
Select `Templates > Gradle` and add the necessary system properties to the `VM options` field.

For example to enable the Configuration Cache, turning problems into warnings, add the following:

[source,text]
----
-Dorg.gradle.configuration-cache=true -Dorg.gradle.configuration-cache.problems=warn
----

You can also choose to only enable it for a given run configuration.
In this case, leave the `Templates > Gradle` configuration untouched and edit each run configuration as you see fit.

Using these methods together, you can enable the Configuration Cache globally while disabling it for certain run configurations, or vice versa.

[TIP]
====
You can use the link:https://github.com/JetBrains/gradle-idea-ext-plugin[gradle-idea-ext-plugin] to configure IntelliJ run configurations from your build.

This is a good way to enable the Configuration Cache only for the IDE.
====

[[config_cache:ide:eclipse]]
=== Eclipse based IDEs

In Eclipse-based IDEs, you can enable the Configuration Cache through Buildship, either globally or per run configuration.

To enable it globally:

1. Go to `Preferences > Gradle`.
2. Add the following JVM arguments:
** `-Dorg.gradle.configuration-cache=true`
** `-Dorg.gradle.configuration-cache.problems=warn`

To enable it for a specific run configuration:

1. Open `Run Configurations....`
2. Select the desired configuration.
3. Navigate to `Project Settings`, check `Override project settings`, and add the same system properties as `JVM arguments`.

Using these methods together, you can enable the Configuration Cache globally while disabling it for certain run configurations, or vice versa.

[[config_cache:plugins]]
== Supported Plugins

The Configuration Cache introduces new requirements for plugin implementations.
As a result, both Core Gradle plugins and Community Plugins need to be adjusted to ensure compatibility.

This section provides details on the current support in:

- <<configuration_cache#config_cache:plugins:core, Core Gradle Plugins>>
- <<configuration_cache#config_cache:plugins:community, Community Plugins>>

[[config_cache:plugins:core]]
=== Core Gradle Plugins

Most <<plugin_reference#plugin_reference, Core Gradle Plugins>> support configuration caching at this time:

[cols=3*]
|===
h| JVM languages and frameworks
h| Native languages
h| Packaging and distribution

a|
[horizontal]
link:{gradle-issues}13457[[.green]#✓#]:: <<java_plugin.adoc#java_plugin,Java>>
link:{gradle-issues}13458[[.green]#✓#]:: <<java_library_plugin.adoc#java_library_plugin,Java Library>>
link:{gradle-issues}13459[[.green]#✓#]:: <<java_platform_plugin.adoc#java_platform_plugin,Java Platform>>
link:{gradle-issues}13460[[.green]#✓#]:: <<groovy_plugin.adoc#groovy_plugin,Groovy>>
link:{gradle-issues}13461[[.green]#✓#]:: <<scala_plugin.adoc#scala_plugin,Scala>>
link:{gradle-issues}13462[[.green]#✓#]:: <<antlr_plugin.adoc#antlr_plugin,ANTLR>>

a|
[horizontal]
link:{gradle-issues}30806[[.green]#✓#]:: <<cpp_application_plugin.adoc#cpp_application_plugin,C++ Application>>
link:{gradle-issues}30806[[.green]#✓#]:: <<cpp_library_plugin.adoc#cpp_library_plugin,C++ Library>>
link:{gradle-issues}13514[[.green]#✓#]:: <<cpp_unit_test_plugin.adoc#cpp_unit_test_plugin,C++ Unit Test>>
link:{gradle-issues}13515[[.green]#✓#]:: <<swift_application_plugin.adoc#swift_application_plugin,Swift Application>>
link:{gradle-issues}13487[[.green]#✓#]:: <<swift_library_plugin.adoc#swift_library_plugin,Swift Library>>
link:{gradle-issues}13488[[.green]#✓#]:: <<xctest_plugin.adoc#xctest_plugin,XCTest>>

a|
[horizontal]
link:{gradle-issues}13463[[.green]#✓#]:: <<application_plugin.adoc#application_plugin,Application>>
link:{gradle-issues}13466[[.green]#✓#]:: <<war_plugin.adoc#war_plugin,WAR>>
link:{gradle-issues}13467[[.green]#✓#]:: <<ear_plugin.adoc#ear_plugin,EAR>>
link:{gradle-issues}24329[[.yellow]#⚠#]:: <<publishing_maven.adoc#publishing_maven,Maven Publish>>
link:{gradle-issues}24328[[.yellow]#⚠#]:: <<publishing_ivy.adoc#publishing_ivy,Ivy Publish>>
link:{gradle-issues}13464[[.green]#✓#]:: <<distribution_plugin.adoc#distribution_plugin,Distribution>>
link:{gradle-issues}13465[[.green]#✓#]:: <<java_library_distribution_plugin.adoc#java_library_distribution_plugin,Java Library Distribution>>

h| Code analysis
h| IDE project files generation
h| Utility

a|
[horizontal]
link:{gradle-issues}13475[[.green]#✓#]:: <<checkstyle_plugin.adoc#checkstyle_plugin,Checkstyle>>
link:{gradle-issues}13478[[.green]#✓#]:: <<codenarc_plugin.adoc#codenarc_plugin,CodeNarc>>
link:{gradle-issues}13477[[.green]#✓#]:: <<jacoco_plugin.adoc#jacoco_plugin,JaCoCo>>
[.green]#✓#:: <<jacoco_report_aggregation_plugin#jacoco_report_aggregation_plugin,JaCoCo Report Aggregation>>
link:{gradle-issues}13476[[.green]#✓#]:: <<pmd_plugin.adoc#pmd_plugin,PMD>>
[.green]#✓#:: <<test_report_aggregation_plugin#test_report_aggregation_plugin,Test Report Aggregation>>

a|
[horizontal]
link:{gradle-issues}13479[[.red]#✖#]:: <<eclipse_plugin.adoc#eclipse_plugin,Eclipse>>
link:{gradle-issues}13480[[.red]#✖#]:: <<idea_plugin.adoc#idea_plugin,IntelliJ IDEA>>
link:{gradle-issues}13482[[.green]#✓#]:: <<visual_studio_plugin.adoc#visual_studio_plugin,Visual Studio>>
link:{gradle-issues}13483[[.green]#✓#]:: <<xcode_plugin.adoc#xcode_plugin,Xcode>>

a|
[horizontal]
link:{gradle-issues}13455[[.green]#✓#]:: <<base_plugin.adoc#base_plugin,Base>>
link:{gradle-issues}13456[[.green]#✓#]:: <<build_init_plugin.adoc#build_init_plugin,Build Init>>
link:{gradle-issues}13470[[.green]#✓#]:: <<signing_plugin.adoc#signing_plugin,Signing>>
link:{gradle-issues}24537[[.green]#✓#]:: <<java_gradle_plugin.adoc#java_gradle_plugin,Java Plugin Development>>
link:{gradle-issues}23029[[.green]#✓#]:: <<implementing_gradle_plugins_precompiled.adoc#implemention_precompiled_plugins,Groovy DSL Plugin Development>>
link:{gradle-issues}13472[[.green]#✓#]:: <<kotlin_dsl.adoc#sec:kotlin-dsl_plugin,Kotlin DSL Plugin Development>>
link:{gradle-issues}13473[[.green]#✓#]:: <<project_report_plugin.adoc#project_report_plugin,Project Report Plugin>>

|===

[horizontal]
[.green]#✓#:: Supported plugin
[.yellow]#⚠#:: Partially supported plugin
[.red]#✖#:: Unsupported plugin

[[config_cache:plugins:community]]
=== Community Plugins

Please refer to issue link:{gradle-issues}13490[gradle/gradle#13490] to learn about the status of Community Plugins.

[[config_cache:troubleshooting]]
== Troubleshooting

This section provides general guidelines for resolving issues with the Configuration Cache, whether in your build logic or Gradle plugins.

When Gradle encounters a problem serializing the necessary state to execute tasks, it generates an HTML report detailing the detected issues.
The console output includes a clickable link to this report, allowing you to investigate the root causes.

Consider the following build script, which contains two issues:

====
include::sample[dir="snippets/configurationCache/problemsKotlin/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/configurationCache/problemsGroovy/groovy",files="build.gradle[]"]
====
<1> <<config_cache:requirements:reading_sys_props_and_env_vars, A system property read at configuration time>>
<2> <<config_cache:requirements:use_project_during_execution, Using the `Project` object at execution time>>

Running the task fails with the following output:

[soure,text]
----
❯ ./gradlew --configuration-cache someTask -DsomeDestination=dest
...
include::{snippetsPath}/configurationCache/problemsGroovy/tests/fail.out[]
Configuration Cache entry discarded with 1 problem.
----

Since a problem was detected, Gradle discards the Configuration Cache entry, preventing reuse in future builds.

The linked HTML report provides details about the detected problems:

image::configuration-cache/problems-report.png[]

The report presents issues in two ways:

- *Grouped by message* → Quickly identify recurring problem types.
- *Grouped by task* → Identify which tasks are causing problems.

Expanding the problem tree helps locate the root cause within the object graph.

Additionally, the report lists detected build configuration inputs, such as system properties, environment variables, and value suppliers accessed during configuration:

image::configuration-cache/inputs-report.png[]

[TIP]
====
Each problem entry in the report includes links to relevant <<configuration_cache#config_cache:requirements, Configuration Cache requirements>> for guidance on resolving the issue, as well as any related <<configuration_cache#config_cache:not_yet_implemented, Not Yet Implemented features>>.

When modifying your build or plugin, consider <<configuration_cache#config_cache:testing, Testing your Build Logic with TestKit>> to verify changes.
====

At this stage, you can either ignore the problems (<<configuration_cache#config_cache:usage:ignore_problems,turn them into warnings>>) to continue exploring Configuration Cache behavior, or fix the issues immediately.

To continue using the Configuration Cache while observing problems, run:

[source,text]
----
❯ ./gradlew --configuration-cache --configuration-cache-problems=warn someTask -DsomeDestination=dest
include::{snippetsPath}/configurationCache/problemsGroovy/tests/store.out[]
Configuration Cache entry stored with 1 problem.
❯ ./gradlew --configuration-cache --configuration-cache-problems=warn someTask -DsomeDestination=dest
include::{snippetsPath}/configurationCache/problemsGroovy/tests/load.out[]
Configuration Cache entry reused with 1 problem.
----

Gradle will successfully store and reuse the Configuration Cache while continuing to report the problem.

The report and console logs provide links to guidance on resolving detected issues.

Here’s a corrected version of the example build script:

====
include::sample[dir="snippets/configurationCache/problemsFixed/kotlin",files="build.gradle.kts[tags=fixed]"]
include::sample[dir="snippets/configurationCache/problemsFixed/groovy",files="build.gradle[tags=fixed]"]
====
<1> We turned our ad-hoc task into a proper task class,
<2> with inputs and outputs declaration,
<3> and injected with the `FileSystemOperations` service, a supported replacement for <<configuration_cache#config_cache:requirements:use_project_during_execution, `project.copy {}`>>.

After fixing these issues, running the task twice successfully reuses the Configuration Cache:

[source,text]
----
❯ ./gradlew --configuration-cache someTask -DsomeDestination=dest
include::{snippetsPath}/configurationCache/problemsFixed/tests/store.out[]
Configuration Cache entry stored.
❯ ./gradlew --configuration-cache someTask -DsomeDestination=dest
include::{snippetsPath}/configurationCache/problemsFixed/tests/load.out[]
Configuration Cache entry reused.
----

If a build input changes (e.g., a system property value), the Configuration Cache entry becomes invalid, requiring a new configuration phase:

----
❯ ./gradlew --configuration-cache someTask -DsomeDestination=another
include::{snippetsPath}/configurationCache/problemsFixed/tests/store-another.out[]
Configuration Cache entry stored.
----

The cache entry was invalidated because the system property was read at configuration time, forcing Gradle to re-run configuration when its value changed.

A better approach is to use a provider to defer reading the system property until execution time:

====
include::sample[dir="snippets/configurationCache/problemsFixedReuse/kotlin",files="build.gradle.kts[tags=fixed-reuse]"]
include::sample[dir="snippets/configurationCache/problemsFixedReuse/groovy",files="build.gradle[tags=fixed-reuse]"]
====
<1> We wired the system property provider directly, without reading it at configuration time.

Now, the cache entry remains reusable even when changing the system property:

----
❯ ./gradlew --configuration-cache someTask -DsomeDestination=dest
include::{snippetsPath}/configurationCache/problemsFixedReuse/tests/store.out[]
Configuration Cache entry stored.
❯ ./gradlew --configuration-cache someTask -DsomeDestination=another
include::{snippetsPath}/configurationCache/problemsFixedReuse/tests/load-another.out[]
Configuration Cache entry reused.
----

With these fixes in place, this task is fully compatible with the Configuration Cache.

Continue reading to learn how to fully adopt the Configuration Cache for your build and plugins.

[[config_cache:task_opt_out]]
=== Declare a Task Incompatible with the Configuration Cache

You can explicitly mark a task as incompatible with the Configuration Cache using the link:{javadocPath}/org/gradle/api/Task.html#notCompatibleWithConfigurationCache-java.lang.String-[`Task.notCompatibleWithConfigurationCache()`] method:

====
include::sample[dir="snippets/dependencyManagement/dependencyLocking-lockingAllConfigurations/kotlin",files="build.gradle.kts[tags=resolve-all]"]
include::sample[dir="snippets/dependencyManagement/dependencyLocking-lockingAllConfigurations/groovy",files="build.gradle[tags=resolve-all]"]
====

When a task is marked as incompatible:

- Configuration Cache problems *in that task* will no longer cause the build to fail.
- Gradle discards the configuration state at the end of the build if an incompatible task is executed.

This mechanism can be useful during migration, allowing you to temporarily opt out tasks that require more extensive changes to become Configuration Cache-compatible.

For more details, refer to the link:{javadocPath}/org/gradle/api/Task.html#notCompatibleWithConfigurationCache-java.lang.String-[method] documentation.

[[config_cache:integrity_check]]
=== Using integrity checks to debug store and load issues

To reduce entry size and improve performance, Gradle performs minimal integrity checks when writing and reading data.
However, this approach can make troubleshooting issues more difficult, especially when dealing with concurrency problems or serialization errors.
An incorrectly stored object may not be detected immediately but could lead to misleading or misattributed errors when reading cached data later.

To make debugging easier, Gradle provides an option to enable stricter integrity checks.
This setting helps identify inconsistencies earlier but may slow down cache operations and significantly increase the cache entry size.
To enable stricter integrity checks, add the following line to your `gradle.properties` file:

[source,properties]
.gradle.properties
----
org.gradle.configuration-cache.integrity-check=true
----

For example, let's look at a type that implements a custom serialization protocol incorrectly:

[source,java]
----
include::{snippetsPath}/configurationCache/integrityChecks/common/buildSrc/src/main/java/User.java[tags=broken-type]
----
<1> `writeObject` serializes both fields.
<2> `readObject` reads only the first field, leaving the remaining data in the stream.

Such a type will cause problems when used as part of a task state, because the configuration cache will try to interpret the remaining unread part of the object as some new value:

[source,java]
----
include::{snippetsPath}/configurationCache/integrityChecks/common/buildSrc/src/main/java/GreetTask.java[tags=task-with-broken-type]
----

When running without the integrity check, you may encounter cryptic failure messages, possibly accompanied by induced configuration cache problems:

----
❯ gradle --configuration-cache greet
...
* What went wrong:
Index 4 out of bounds for length 3
----

These errors might not immediately point to the root cause, making debugging more challenging.
It might be really hard to connect an invalid index error to a serialization issue, for example.

Rerunning the build with the integrity check enabled provides a much more precise diagnostic, helping you pinpoint the source of the issue faster:

----
❯ gradle --configuration-cache -Dorg.gradle.configuration-cache.integrity-check=true greet
...
include::{snippetsPath}/configurationCache/integrityChecks/tests/fail.out[]
----

You can immediately see the name of the offending task and the field that contains the broken data.

Keep in mind that this attribution is best-effort: it should be accurate in most cases, but in rare instances, it may be confused by certain byte patterns.

[WARNING]
====
The integrity check relies on additional metadata stored within the cache. Therefore, it cannot be used to diagnose entries already corrupted prior to enabling the integrity check.
====

The current integrity checks primarily focus on identifying serialization protocol issues rather than general data corruption.
Consequently, they are less effective against hardware-related problems, such as bit rot or damaged storage sectors.
Due to these limitations and the performance overhead introduced by integrity checks, we recommend enabling them selectively as a troubleshooting measure rather than leaving them permanently enabled.

[[config_cache:adoption]]
== Configuration Cache Adoption Steps

An important prerequisite is to keep your Gradle and plugins up to date.
The following steps outline a recommended approach for successful adoption.
These steps apply to both builds and plugins.

While following this process, refer to the HTML report and the solutions explained in the <<configuration_cache#config_cache:requirements, requirements>> section.

. Start with `help`
+
Always begin by testing your build or plugin with the simplest task: `help`. This exercises the minimal configuration phase of your build or plugin.

. Progressively target useful tasks
+
Avoid running `build` right away. Instead:

- Use `--dry-run` to identify configuration time problems first.
- When working on a build, focus on your development feedback loop, such as running tests after modifying source code.
- When working on a plugin, progressively target the contributed or configured tasks.

. Explore by turning problems into warnings
+
Don't stop at the first build failure—<<configuration_cache#config_cache:usage:ignore_problems, turn problems into warnings>> to better understand how your build and plugins behave. If a build fails:

- Use the HTML report to analyze the reported problems.
- Continue testing more tasks to get a full picture of the issues affecting your build and plugins.
- Keep in mind that when turning problems into warnings, you may need to <<configuration_cache#config_cache:usage:invalidate, manually invalidate the cache>> in case of unexpected behavior.

. Step back and fix problems iteratively
+
Once you have a clear understanding of the issues, start fixing them iteratively. Use the HTML report and this documentation to guide your process:

- Begin with problems reported when _storing_ the Configuration Cache.
- Once those are fixed, move on to addressing any problems encountered when _loading_ the Configuration Cache.

. Report encountered issues
+
If you encounter issues with a <<configuration_cache#config_cache:not_yet_implemented, Gradle Feature>> or a <<configuration_cache#config_cache:plugins:core, Core Gradle Plugin>> that is not covered by this documentation, report it to link:https://github.com/gradle/gradle/issues/new/choose[`gradle/gradle`].
+
For community Gradle plugins, check if the issue is already listed at link:{gradle-issues}13490[gradle/gradle#13490] and report it to the plugin's issue tracker if necessary.
+
A good bug report should include:

** A link to this documentation.
** The plugin version you tested.
** Any custom plugin configuration, or ideally a reproducer build.
** A description of what fails (e.g., problems with a specific task).
** A copy of the build failure output.
** The self-contained `configuration-cache-report.html` file.

. Test, test, test
+
Add tests for your build logic to catch issues early.
See <<configuration_cache#config_cache:testing, Testing Your Build Logic>> for details on testing Configuration Cache compatibility.
This will help during iterations and prevent regressions.

. Roll it out to your team
+
Once your developer workflow (e.g., running tests from the IDE) is stable, consider enabling the Configuration Cache for your team:

- Initially, introduce it as an opt-in feature.
- If necessary, turn problems into warnings and set a maximum number of allowed problems in your `gradle.properties` file.
- Keep the Configuration Cache disabled by default, and encourage team members to opt in by configuring their IDE run settings.
- When more workflows are stable, reverse this approach:
** Enable the Configuration Cache by default.
** Configure CI to disable it where needed.
** Communicate any unsupported workflows that require disabling the Configuration Cache.

[[config_cache:adoption:reacting]]
=== Reacting to the Configuration Cache in the Build

Build logic or plugin implementations can detect whether the Configuration Cache is enabled for a given build and adjust behavior accordingly.

The link:{javadocPath}/org/gradle/api/configuration/BuildFeature.html#getActive--[active] status of the Configuration Cache is provided in the corresponding link:{javadocPath}/org/gradle/api/configuration/BuildFeatures.html#getConfigurationCache--[build feature].
You can access it by <<service_injection.adoc#service_injection, injecting>> the link:{javadocPath}/org/gradle/api/configuration/BuildFeatures.html[`BuildFeatures`] service into your code.

This information can be used to:

- Configure plugin features differently when the Configuration Cache is enabled.
- Disable an optional feature that is not yet compatible with the Configuration Cache.
- Provide additional guidance to users, such as informing them of temporary limitations or suggesting adjustments to their setup.

[[config_cache:adoption:changes_in_behavior]]
=== Adopting changes in the configuration cache behavior

Gradle releases continuously enhance the Configuration Cache by detecting more cases where configuration logic interacts with the environment.
These improvements increase cache correctness by preventing false cache hits but also introduce stricter rules that plugins and build logic must follow for optimal caching.

Some newly detected configuration inputs may not impact the configured tasks but can still cause cache invalidation.
To minimize unnecessary cache misses, follow these steps:

* Identify problematic configuration inputs using the <<configuration_cache#config_cache:troubleshooting, Configuration Cache report>>.
** Fix undeclared configuration inputs accessed by project build logic.
** Report issues caused by third-party plugins to their maintainers and update plugins once they are fixed.
* Use opt-out options for specific cases to temporarily revert to earlier behavior and prevent Gradle from tracking certain inputs.
This can help mitigate performance issues caused by outdated plugins.

It is possible to _temporarily_ opt out of configuration input detection in the following cases:

1. Gradle now tracks file system interactions, including checks such as `File.exists()` or `File.isFile()`, as configuration inputs.
+
To prevent input tracking from invalidating the cache due to these file system checks, use the `org.gradle.configuration-cache.inputs.unsafe.ignore.file-system-checks` property in `gradle.properties`.
List the paths to be ignored, relative to the root project directory, separated by `;`.
Wildcards (`*` for segments, `pass:[**]` for multiple segments) are supported.
Paths prefixed with `~/` are relative to the user’s home directory.
For example:
+
[source,text]
.gradle.properties
----
org.gradle.configuration-cache.inputs.unsafe.ignore.file-system-checks=\
    ~/.third-party-plugin/*.lock;\
    ../../externalOutputDirectory/**;\
    build/analytics.json
----
2. Prior to Gradle 8.4, some undeclared configuration inputs that were never used during configuration could still be read when the Configuration Cache serialized the task graph.
However, these changes did not invalidate the cache.
+
Starting in Gradle 8.4, these undeclared inputs are correctly tracked and now cause cache invalidation.
+
To temporarily revert to the previous behavior, set the the Gradle property `org.gradle.configuration-cache.inputs.unsafe.ignore.in-serialization` to `true`.

Use these opt-out options sparingly and only if they do not impact task execution results.
These options are intended as temporary workarounds and will be removed in future Gradle releases.

[[config_cache:testing]]
== Testing your Build Logic

Gradle TestKit is a library designed to facilitate testing Gradle plugins and build logic.
For general guidance on using TestKit, refer to the <<test_kit.adoc#test_kit, dedicated chapter>>.

To test your build logic with the Configuration Cache enabled, pass the `--configuration-cache` argument to link:{javadocPath}/org/gradle/testkit/runner/GradleRunner.html[`GradleRunner`], or use one of the other methods described in <<configuration_cache.adoc#config_cache:usage:enable, Enabling the Configuration Cache>>.

To properly test Configuration Cache behavior, tasks must be executed twice:

====
include::sample[dir="snippets/configurationCache/testKit/kotlin",files="src/test/kotlin/org/example/BuildLogicFunctionalTest.kt[tags=functional-test-configuration-cache]"]
include::sample[dir="snippets/configurationCache/testKit/groovy",files="src/test/groovy/org/example/BuildLogicFunctionalTest.groovy[tags=functional-test-configuration-cache]"]
====
<1> First run primes the Configuration Cache.
<2> Second run reuses the Configuration Cache.
<3> Assert that the Configuration Cache gets reused.

If Gradle encounters problems with the Configuration Cache, it will fail the build and report the issues, causing the test to fail.

[TIP]
====
A recommended approach for Gradle plugin authors is to run the entire test suite with the Configuration Cache enabled.
This ensures compatibility with a supported Gradle version.

- If your plugin already supports multiple Gradle versions and has version-specific tests, enable Configuration Cache testing starting with the first supported version.
- If immediate full support is not feasible, consider writing tests that:
** Run all plugin-contributed tasks multiple times.
** Assert expected task states, such as `UP_TO_DATE` and `FROM_CACHE` behavior.
====

[[config_cache:requirements]]
== Configuration Cache Requirements

To capture and reload the task graph state using the Configuration Cache, Gradle enforces specific requirements on tasks and build logic.
Any violation of these requirements is reported as a Configuration Cache "problem," which causes the build to fail.

In most cases, these requirements expose undeclared inputs, making builds more strict, correct, and reliable.
Using the Configuration Cache is effectively an opt-in to these improvements.

The following sections describe each requirement and provide guidance on resolving issues in your build.

[[config_cache:requirements:disallowed_types]]
=== Certain Types must not be Referenced by Tasks

Some types must not be referenced by task fields or in task actions (such as `doFirst {}` or `doLast {}`).

These types fall into the following categories:

* Live JVM state types
* Gradle model types
* Dependency management types

These restrictions exist because these types cannot easily be stored or reconstructed by the Configuration Cache.

==== Live JVM State Types

Live JVM state types (e.g., `ClassLoader`, `Thread`, `OutputStream`, `Socket`) are disallowed, as they do not represent task inputs or outputs.

The only exceptions are standard streams (`System.in`, `System.out`, `System.err`), which can be used, for example, as parameters for link:{groovyDslPath}/org.gradle.api.tasks.Exec.html[`Exec`] and link:{groovyDslPath}/org.gradle.api.tasks.JavaExec.html[`JavaExec`] tasks.

==== Gradle Model Types

Gradle model types (e.g., `Gradle`, `Settings`, `Project`, `SourceSet`, `Configuration`) are often used to pass task inputs that should instead be explicitly declared.

For example, instead of referencing a Project to retrieve `project.version` at execution time, declare the project version as a `Property<String>` input.
Similarly, instead of referencing a `SourceSet` for source files or classpath resolution, declare these as a `FileCollection` input.

==== Dependency Management Types

The same requirement applies to dependency management types with some nuances.

Some dependency management types, such as `Configuration` and `SourceDirectorySet`, should not be used as task inputs because they contain unnecessary state and are not precise.
Use a less specific type that gives necessary features instead:

* If referencing a `Configuration` to get resolved files, declare a `FileCollection` input.
* If referencing a `SourceDirectorySet`, declare a `FileTree` input.

Additionally, referencing resolved dependency results is disallowed (e.g., `ArtifactResolutionQuery`, `ResolvedArtifact`, `ArtifactResult`).
Instead:

* Use a `Provider<ResolvedComponentResult>` from `ResolutionResult.getRootComponent()`.
* Use `ArtifactCollection.getResolvedArtifacts()`, which returns a `Provider<Set<ResolvedArtifactResult>>`.

Tasks should avoid referencing _resolved_ results and instead rely on lazy specifications to defer dependency resolution until execution time.

Some types, such as `Publication` or `Dependency`, are not serializable but could be made so in the future.
Gradle may allow them as task inputs if necessary.

The following task references a `SourceSet`, which is not allowed:

====
include::sample[dir="snippets/configurationCache/disallowedTypes/kotlin",files="build.gradle.kts[tags=task-type]"]
include::sample[dir="snippets/configurationCache/disallowedTypes/groovy",files="build.gradle[tags=task-type]"]
====
<1> This will be reported as a problem because referencing `SourceSet` is not allowed

The following is the fixed version:

====
include::sample[dir="snippets/configurationCache/disallowedTypesFixed/kotlin",files="build.gradle.kts[tags=task-type]"]
include::sample[dir="snippets/configurationCache/disallowedTypesFixed/groovy",files="build.gradle[tags=task-type]"]
====
<1> No more problems reported, we now reference the supported type `FileCollection`

If an ad-hoc task in a script captures a disallowed reference in a `doLast {}` closure:

====
include::sample[dir="snippets/configurationCache/disallowedTypes/kotlin",files="build.gradle.kts[tags=ad-hoc-task]"]
include::sample[dir="snippets/configurationCache/disallowedTypes/groovy",files="build.gradle[tags=ad-hoc-task]"]
====
<1> This will be reported as a problem because the `doLast {}` closure is capturing a reference to the `SourceSet`

You still need to fulfil the same requirement, that is not referencing a disallowed type.

This is how the task declaration above can be fixed:

====
include::sample[dir="snippets/configurationCache/disallowedTypesFixed/kotlin",files="build.gradle.kts[tags=ad-hoc-task]"]
include::sample[dir="snippets/configurationCache/disallowedTypesFixed/groovy",files="build.gradle[tags=ad-hoc-task]"]
====
<1> No more problems reported, the `doLast {}` closure now only captures `classpath` which is of the supported `FileCollection` type

Sometimes, a disallowed type is indirectly referenced through another type.
For example, a task may reference an allowed type that, in turn, references a disallowed type.
The hierarchical view in the HTML problem report can help you trace such issues and identify the offending reference.

[[config_cache:requirements:use_project_during_execution]]
=== Using the `Project` Object at Execution Time

Tasks must not use any `Project` objects during execution.
This includes calling `Task.getProject()` while a task is running.

Some cases can be resolved similarly to those described in <<configuration_cache#config_cache:requirements:disallowed_types, disallowed types>>.

Often, equivalent functionality is available on both `Project` and `Task`.
For example:

* If you need a `Logger`, use `Task.logger` instead of `Project.logger`.
* For file operations, use <<service_injection.adoc#service_injection, injected services>> rather than `Project` methods.

The following task incorrectly references the `Project` object at execution time:

====
include::sample[dir="snippets/configurationCache/projectAtExecution/kotlin",files="build.gradle.kts[tags=task-type]"]
include::sample[dir="snippets/configurationCache/projectAtExecution/groovy",files="build.gradle[tags=task-type]"]
====
<1> This will be reported as a problem because the task action is using the `Project` object at execution time

Fixed version:

====
include::sample[dir="snippets/configurationCache/projectAtExecutionFixed/kotlin",files="build.gradle.kts[tags=task-type]"]
include::sample[dir="snippets/configurationCache/projectAtExecutionFixed/groovy",files="build.gradle[tags=task-type]"]
====
<1> No more problem reported, the injected `FileSystemOperations` service is supported as a replacement for `project.copy {}`

If the same problem occurs in an ad-hoc task in a script:

====
include::sample[dir="snippets/configurationCache/projectAtExecution/kotlin",files="build.gradle.kts[tags=ad-hoc-task]"]
include::sample[dir="snippets/configurationCache/projectAtExecution/groovy",files="build.gradle[tags=ad-hoc-task]"]
====
<1> This will be reported as a problem because the task action is using the `Project` object at execution time

Fixed version:

====
include::sample[dir="snippets/configurationCache/projectAtExecutionFixed/kotlin",files="build.gradle.kts[tags=ad-hoc-task]"]
include::sample[dir="snippets/configurationCache/projectAtExecutionFixed/groovy",files="build.gradle[tags=ad-hoc-task]"]
====
<1> Services can't be injected directly in scripts, we need an extra type to convey the injection point
<2> Create an instance of the extra type using `project.object` outside the task action
<3> No more problem reported, the task action references `injected` that provides the `FileSystemOperations` service, supported as a replacement for `project.copy {}`

Fixing ad-hoc tasks in scripts requires additional effort, making it a good opportunity to refactor them into proper task classes.

The table below lists recommended replacements for commonly used `Project` methods:

[cols="a,a",options="header"]
|===
| Instead of:
| Use:

| `project.rootDir`
| A task input or output property or a script variable to capture the result of using `project.rootDir` to calculate the actual parameter.

| `project.projectDir`
| A task input or output property or a script variable to capture the result of using `project.projectDir` to calculate the actual parameter.

| `project.buildDir`
| A task input or output property or a script variable to capture the result of using `project.buildDir` to calculate the actual parameter.

| `project.name`
| A task input or output property or a script variable to capture the result of using `project.name` to calculate the actual parameter.

| `project.description`
| A task input or output property or a script variable to capture the result of using `project.description` to calculate the actual parameter.

| `project.group`
| A task input or output property or a script variable to capture the result of using `project.group` to calculate the actual parameter.

| `project.version`
| A task input or output property or a script variable to capture the result of using `project.version` to calculate the actual parameter.

| `project.properties`, `project.property(name)`, `project.hasProperty(name)`, `project.getProperty(name)` or `project.findProperty(name)`
| link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:gradleProperty(java.lang.String)[Value providers for Gradle properties].

| `project.logger`
| link:{javadocPath}/org/gradle/api/Task.html#getLogger--[Task.logger]

| `project.provider {}`
| link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:provider(java.util.concurrent.Callable)[ProviderFactory.provider {}]

| `project.file(path)`
| A task input or output property or a script variable to capture the result of using `project.file(file)` to calculate the actual parameter.

| `project.uri(path)`
| A task input or output property or a script variable to capture the result of using `project.uri(path)` to calculate the actual parameter. Otherwise, `File.toURI()` or some other JVM API can be used.

| `project.relativePath(path)`
| link:{javadocPath}/org/gradle/api/file/ProjectLayout.html#getProjectDirectory--[ProjectLayout.projectDirectory].link:{javadocPath}/org/gradle/api/file/Directory.html#file-java.lang.String-[file(path)]

| `project.files(paths)`
| link:{javadocPath}/org/gradle/api/model/ObjectFactory.html#fileCollection--[ObjectFactory.fileCollection()].link:{javadocPath}/org/gradle/api/file/ConfigurableFileCollection.html#from-java.lang.Object...-[from(paths)]

| `project.fileTree(paths)`
| link:{javadocPath}/org/gradle/api/model/ObjectFactory.html#fileTree--[ObjectFactory.fileTree()].link:{javadocPath}/org/gradle/api/file/ConfigurableFileTree.html#from-java.lang.Object-[from(dir)]

| `project.zipTree(path)`
| link:{javadocPath}/org/gradle/api/file/ArchiveOperations.html#zipTree-java.lang.Object-[ArchiveOperations.zipTree(path)]

| `project.tarTree(path)`
| link:{javadocPath}/org/gradle/api/file/ArchiveOperations.html#tarTree-java.lang.Object-[ArchiveOperations.tarTree(path)]

| `project.resources`
| A task input or output property or a script variable to capture the result of using `project.resource` to calculate the actual parameter.

| `project.copySpec {}`
| link:{javadocPath}/org/gradle/api/file/FileSystemOperations.html#copySpec--[FileSystemOperations.copySpec {}]

| `project.copy {}`
| link:{javadocPath}/org/gradle/api/file/FileSystemOperations.html#copy-org.gradle.api.Action-[FileSystemOperations.copy {}]

| `project.sync {}`
| link:{javadocPath}/org/gradle/api/file/FileSystemOperations.html#sync-org.gradle.api.Action-[FileSystemOperations.sync {}]

| `project.delete {}`
| link:{javadocPath}/org/gradle/api/file/FileSystemOperations.html#delete-org.gradle.api.Action-[FileSystemOperations.delete {}]

| `project.mkdir(path)`
| The Kotlin, Groovy or Java API available to your build logic.

| `project.exec {}`
| link:{javadocPath}/org/gradle/process/ExecOperations.html#exec-org.gradle.api.Action-[ExecOperations.exec {}]

| `project.javaexec {}`
| link:{javadocPath}/org/gradle/process/ExecOperations.html#javaexec-org.gradle.api.Action-[ExecOperations.javaexec {}]

| `project.ant {}`
| link:{javadocPath}/org/gradle/api/Task.html#getAnt--[Task.ant]

| `project.createAntBuilder()`
| link:{javadocPath}/org/gradle/api/Task.html#getAnt--[Task.ant]

|===

[[config_cache:requirements:task_access]]
=== Accessing a Task Instance from Another Instance

Tasks must not directly access the state of another task instance.
Instead, they should be connected using <<lazy_configuration#working_with_task_dependencies_in_lazy_properties, inputs and outputs relationships>>.

This requirement ensures that tasks remain isolated and correctly cacheable.
As a result, it is unsupported to write tasks that configure other tasks at execution time.

[[config_cache:requirements:shared_objects]]
=== Sharing mutable objects

When storing a task in the Configuration Cache, all objects referenced through the task’s fields are serialized.

In most cases, deserialization preserves reference equality—if two fields `a` and `b` reference the same instance at configuration time, they will still reference the same instance after deserialization (`a == b`, or `a === b` in Groovy/Kotlin syntax).

However, for performance reasons, certain classes—such as `java.lang.String`, `java.io.File`, and many `java.util.Collection` implementations—are serialized without preserving reference equality.
After deserialization, fields that referred to these objects may reference different but equal instances.

Consider a task that stores a user-defined object and an `ArrayList` as task fields:

====
include::sample[dir="snippets/configurationCache/sharedObjects/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/configurationCache/sharedObjects/groovy",files="build.gradle[]"]
====
<1> `doLast` action captures the references from the enclosing scope. These captured references are also serialized to the Configuration Cache.
<2> Compare the reference to an object of user-defined class stored in the task field and the reference captured in the `doLast` action.
<3> Compare the reference to `ArrayList` instance stored in the task field and the reference captured in the `doLast` action.
<4> Check the equality of stored and captured lists.

Without Configuration Cache, reference equality is preserved in both cases:

----
❯ ./gradlew --no-configuration-cache checkEquality
include::{snippetsPath}/configurationCache/sharedObjects/tests/sharingObjectsWithoutConfigurationCache.out[]
----

With Configuration Cache enabled, only user-defined object references remain identical.
List references are different, although the lists themselves remain equal:

----
❯ ./gradlew --configuration-cache checkEquality
include::{snippetsPath}/configurationCache/sharedObjects/tests/sharingObjectsWithConfigurationCache.out[]
----

Best Practices:

* Avoid sharing mutable objects between configuration and execution phases.
* If sharing state is necessary, wrap it in a user-defined class.
* Do not rely on reference equality for standard Java, Groovy, Kotlin, or Gradle-defined types.

Reference equality is never preserved between tasks—each task is an isolated "realm."
To share objects across tasks, use a <<build_services#build_services, Build Service>> to wrap the shared state.

[[config_cache:requirements:task_extensions]]
=== Accessing Task Extensions or Conventions

Tasks must **not** access conventions, extensions, or extra properties at execution time.

Instead, any value relevant to task execution should be explicitly modeled as a task property to ensure proper caching and reproducibility.

[[config_cache:requirements:build_listeners]]
=== Using Build Listeners

Plugins and build scripts must **not** register build listeners that are created at configuration time and triggered at execution time.
This includes listeners such as `BuildListener` or `TaskExecutionListener`.

Recommended Alternatives:

- Use <<build_services#build_services, Build Services>> to handle execution-time logic.
- Register a Build Service to receive <<build_services#operation_listener, task execution notifications>>.
- Replace `buildFinished` listeners with <<dataflow_actions.adoc#dataflow_action, dataflow actions>> to manage build results.

[[config_cache:requirements:external_processes]]
=== Running External Processes

Plugin and build scripts should avoid running external processes at configuration time.

In general, it is preferred to run external processes in tasks with properly declared inputs and outputs to avoid unnecessary work when the task is `UP-TO-DATE`.
However, if needed, you should only use the configuration-cache-compatible APIs described below instead of Java and Groovy standard APIs, or Gradle-provided methods `Project.exec`, `Project.javaexec`, `ExecOperations.exec`, and `ExecOperations.javaexec`.
The flexibility of these methods prevents Gradle from determining how the calls impact the build configuration, making it difficult to ensure that the Configuration Cache entry can be safely reused.

For simpler cases, when grabbing the output of the process is enough,
link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:exec(org.gradle.api.Action)[`providers.exec()`] and
link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:javaexec(org.gradle.api.Action)[`providers.javaexec()`] can be used:

====
include::sample[dir="snippets/valueProviders/externalProcessProvider/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/valueProviders/externalProcessProvider/groovy",files="build.gradle[]"]
====

For more complex cases, a custom link:{javadocPath}/org/gradle/api/provider/ValueSource.html[`ValueSource`] implementation with injected `ExecOperations` can be used.
This `ExecOperations` instance can be used at configuration time without restrictions:

====
include::sample[dir="snippets/valueProviders/externalProcessValueSource/kotlin",files="build.gradle.kts[tags=value-source]"]
include::sample[dir="snippets/valueProviders/externalProcessValueSource/groovy",files="build.gradle[tags=value-source]"]
====

You can also use standard Java/Kotlin/Groovy process APIs like `java.lang.ProcessBuilder` in the `ValueSource`.

The `ValueSource` implementation can then be used to create a provider with link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:of(java.lang.Class,%20org.gradle.api.Action)[`providers.of`]:

====
include::sample[dir="snippets/valueProviders/externalProcessValueSource/kotlin",files="build.gradle.kts[tags=create-provider]"]
include::sample[dir="snippets/valueProviders/externalProcessValueSource/groovy",files="build.gradle[tags=create-provider]"]
====

In both approaches, if the value of the provider is used at configuration time then it will become a build configuration input.
The external process will be executed for every build to determine if the Configuration Cache is `UP-TO-DATE`, so it is recommended to only call fast-running processes at configuration time.
If the value changes then the cache is invalidated and the process will be run again during this build as part of the configuration phase.

[[config_cache:requirements:reading_sys_props_and_env_vars]]
=== Reading System Properties and Environment Variables

Plugins and build scripts may read system properties and environment variables directly at configuration time with standard Java, Groovy, or Kotlin APIs or with the value supplier APIs.
Doing so makes such variables or properties a build configuration input.
Therefore, changing their value invalidates the Configuration Cache.

The Configuration Cache report includes a list of these build configuration inputs to help track them.

In general, you should avoid reading the value of system properties and environment variables at configuration time to avoid cache misses when these values change.
Instead, you can connect the `Provider` returned by link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:systemProperty(java.lang.String)[`providers.systemProperty()`] or
link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:environmentVariable(java.lang.String)[`providers.environmentVariable()`] to task properties.

Some access patterns that potentially enumerate all environment variables or system properties (for example, calling `System.getenv().forEach()` or using the iterator of its `keySet()`) are discouraged.
In this case, Gradle cannot find out what properties are actual build configuration inputs, so every available property becomes one.
Even adding a new property will invalidate the cache if this pattern is used.

Using a custom predicate to filter environment variables is an example of this discouraged pattern:

====
include::sample[dir="snippets/valueProviders/envVarsSysPropsDont/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/valueProviders/envVarsSysPropsDont/groovy",files="build.gradle[]"]
====

The logic in the predicate is opaque to the Configuration Cache, so all environment variables are considered inputs.
One way to reduce the number of inputs is to always use methods that query a concrete variable name, such as `getenv(String)`, or `getenv().get()`:

====
include::sample[dir="snippets/valueProviders/envVarsSysPropsDo/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/valueProviders/envVarsSysPropsDo/groovy",files="build.gradle[]"]
====

The fixed code above, however, is not exactly equivalent to the original as only an explicit list of variables is supported.
Prefix-based filtering is a common scenario, so there are provider-based APIs to access
link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:systemPropertiesPrefixedBy(java.lang.String)[system properties] and
link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:environmentVariablesPrefixedBy(java.lang.String)[environment variables]:

====
include::sample[dir="snippets/valueProviders/envVarsSysPropsDoPrefix/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/valueProviders/envVarsSysPropsDoPrefix/groovy",files="build.gradle[]"]
====

Note that the Configuration Cache would be invalidated not only when the value of the variable changes or the variable is removed but also
when another variable with the matching prefix is added to the environment.

For more complex use cases a custom link:{javadocPath}/org/gradle/api/provider/ValueSource.html[`ValueSource`] implementation can be used.
System properties and environment variables referenced in the code of the `ValueSource` do not become build configuration inputs, so any processing can be applied.
Instead, the value of the `ValueSource` is recomputed each time the build runs and only if the value changes the Configuration Cache is invalidated.
For example, a `ValueSource` can be used to get all environment variables with names containing the substring `JDK`:

====
include::sample[dir="snippets/valueProviders/envVarsSysPropsDoValueSource/kotlin",files="build.gradle.kts[tags=value-source,create-provider]"]
include::sample[dir="snippets/valueProviders/envVarsSysPropsDoValueSource/groovy",files="build.gradle[tags=value-source,create-provider]"]
====

[[config_cache:requirements:undeclared_file_read]]
=== Undeclared Reading of Files

Plugins and build scripts should not read files directly using the Java, Groovy or Kotlin APIs at configuration time.
Instead, declare files as potential build configuration inputs using the value supplier APIs.

This problem is caused by build logic similar to this:

====
include::sample[dir="snippets/valueProviders/fileContentsDont/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/valueProviders/fileContentsDont/groovy",files="build.gradle[]"]
====

To fix this problem, read files using link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:fileContents(org.gradle.api.file.RegularFile)[`providers.fileContents()`] instead:

====
include::sample[dir="snippets/valueProviders/fileContentsDo/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/valueProviders/fileContentsDo/groovy",files="build.gradle[]"]
====

In general, you should avoid reading files at configuration time, to avoid invalidating Configuration Cache entries when the file content changes.
Instead, you can connect the `Provider` returned by link:{groovyDslPath}/org.gradle.api.provider.ProviderFactory.html#org.gradle.api.provider.ProviderFactory:fileContents(org.gradle.api.file.RegularFile)[`providers.fileContents()`] to task properties.

[[config_cache:requirements:bytecode_modifications_and_isolation]]
=== Bytecode Modifications and Java Agent

To detect the configuration inputs, Gradle modifies the bytecode of classes on the build script classpath, like plugins and their dependencies.
Gradle uses a Java agent to modify the bytecode.
Integrity self-checks of some libraries may fail because of the changed bytecode or the agent's presence.

To work around this, you can use the <<worker_api.adoc#tasks_parallel_worker, Worker API>> with classloader or process isolation to encapsulate the library code.
The bytecode of the worker's classpath is not modified, so the self-checks should pass.
When process isolation is used, the worker action is executed in a separate worker process that doesn't have the Gradle Java agent installed.

In simple cases, when the libraries also provide command-line entry points (`public static void main()` method), you can also use the link:{javadocPath}/org/gradle/api/tasks/JavaExec.html[`JavaExec`] task to isolate the library.

[[config_cache:secrets]]
== Handling of Credentials and Secrets

Currently, the Configuration Cache does not have a built-in mechanism to prevent storing secrets used as inputs.
As a result, secrets may end up in the serialized Configuration Cache entry, which, by default, is stored under `.gradle/configuration-cache` in your project directory.

To mitigate the risk of accidental exposure, Gradle encrypts the Configuration Cache.
When required, Gradle transparently generates a machine-specific secret key, caches it under the
`<<directory_layout.adoc#dir:gradle_user_home,GRADLE_USER_HOME>>` directory, and uses it to encrypt data in the project-specific caches.

To further enhance security, follow these recommendations:

- Secure access to Configuration Cache entries.
- Use `<<directory_layout.adoc#dir:gradle_user_home,GRADLE_USER_HOME>>/gradle.properties` to store secrets.
The content of this file is **not** included in the Configuration Cache—only its fingerprint is.
If storing secrets in this file, ensure access is **properly restricted**.

See link:{gradle-issues}22618[gradle/gradle#22618].

[[config_cache:secrets:configuring_encryption_key]]
=== Providing an Encryption Key with the `GRADLE_ENCRYPTION_KEY` Environment Variable

By default, Gradle automatically generates and manages the encryption key as a Java keystore, stored under the `<<directory_layout.adoc#dir:gradle_user_home,GRADLE_USER_HOME>>` directory.

For environments where this behavior is undesirable—such as when the `<<directory_layout.adoc#dir:gradle_user_home,GRADLE_USER_HOME>>` directory is shared across multiple machines—you can explicitly provide an encryption key using the `GRADLE_ENCRYPTION_KEY` environment variable.

[IMPORTANT]
====
The same encryption key **must be consistently provided** across multiple Gradle runs; otherwise, Gradle will be unable to reuse existing cached configurations.
====

[[config_cache:secrets:generating_encryption_key]]
=== Generating an Encryption Key compatible with `GRADLE_ENCRYPTION_KEY`

To encrypt the Configuration Cache using a user-specified encryption key, Gradle requires the `GRADLE_ENCRYPTION_KEY` environment variable to be set with a valid AES key, encoded as a Base64 string.

You can generate a Base64-encoded AES-compatible key using the following command:

[source,text]
----
❯ openssl rand -base64 16
----

This command works on Linux and macOS, and on Windows if using a tool like Cygwin.

Once generated, set the Base64-encoded key as the value of the `GRADLE_ENCRYPTION_KEY` environment variable:

[source,text]
----
❯ export GRADLE_ENCRYPTION_KEY="your-generated-key-here"
----

[[config_cache:not_yet_implemented]]
== Not Yet Implemented

Support for configuration caching with certain Gradle features is not yet available. These features will be supported in future Gradle releases.

[[config_cache:not_yet_implemented:sharing]]
=== Sharing the Configuration Cache

The Configuration Cache is currently stored locally only.
It can be reused by both hot and cold local Gradle daemons, but it cannot be shared between developers or CI machines.

See link:{gradle-issues}13510[gradle/gradle#13510].

[[config_cache:not_yet_implemented:source_dependencies]]
=== Source Dependencies

Support for link:https://blog.gradle.org/introducing-source-dependencies[source dependencies] is not yet implemented.
With the Configuration Cache enabled, no problem will be reported and the build will fail.

See link:{gradle-issues}13506[gradle/gradle#13506].

[[config_cache:not_yet_implemented:testkit_build_with_java_agent]]
=== Using a Java Agent with Builds run using TestKit

When running builds using <<test_kit#test_kit, TestKit>>, the Configuration Cache can interfere with Java agents, such as the Jacoco agent, that are applied to these builds.

See link:{gradle-issues}25979[gradle/gradle#25979].

[[config_cache:not_yet_implemented:fine_grained_tracking_of_gradle_properties]]
=== Fine-grained Tracking of Gradle Properties as Build Configuration Inputs

Currently, all external sources of Gradle properties—such as `gradle.properties` files (both in project directories and in the `<<directory_layout.adoc#dir:gradle_user_home,GRADLE_USER_HOME>>`), environment variables, system properties that set properties, and properties specified via command-line flags—are considered build configuration inputs, regardless of whether they are actually used during configuration.

However, these sources are not included in the Configuration Cache report.

See link:{gradle-issues}20969[gradle/gradle#20969].

[[config_cache:not_yet_implemented:java_serialization]]
=== Java Object Serialization

Gradle allows objects that support the link:https://docs.oracle.com/javase/8/docs/platform/serialization/spec/serialTOC.html[Java Object Serialization] protocol to be stored in the Configuration Cache.

The implementation is currently limited to serializable classes that
either implement the `java.io.Externalizable` interface, or implement the `java.io.Serializable` interface and define one of the following combination of methods:

- a `writeObject` method combined with a `readObject` method to control exactly which information to store;
- a `writeObject` method with no corresponding `readObject`; `writeObject` must eventually call `ObjectOutputStream.defaultWriteObject`;
- a `readObject` method with no corresponding `writeObject`; `readObject` must eventually call `ObjectInputStream.defaultReadObject`;
- a `writeReplace` method to allow the class to nominate a replacement to be written;
- a `readResolve` method to allow the class to nominate a replacement for the object just read;

The following _Java Object Serialization_ features are **not** supported:

- the `serialPersistentFields` member to explicitly declare which fields are serializable; the member, if present, is ignored; the Configuration Cache considers all but `transient` fields serializable;
- the following methods of `ObjectOutputStream` are not supported and will throw `UnsupportedOperationException`:
** `reset()`, `writeFields()`, `putFields()`, `writeChars(String)`, `writeBytes(String)` and `writeUnshared(Any?)`.

- the following methods of `ObjectInputStream` are not supported and will throw `UnsupportedOperationException`:
** `readLine()`, `readFully(ByteArray)`, `readFully(ByteArray, Int, Int)`, `readUnshared()`, `readFields()`, `transferTo(OutputStream)` and `readAllBytes()`.
- validations registered via `ObjectInputStream.registerValidation` are simply ignored;
- the `readObjectNoData` method, if present, is never invoked;

See link:{gradle-issues}13588[gradle/gradle#13588].

[[config_cache:not_yet_implemented:accessing_top_level_at_execution]]
=== Accessing top-level Methods and Variables of a Build Script at Execution Time

A common approach to reuse logic and data in a build script is to extract repeating bits into top-level methods and variables.
However, calling such methods at execution time is not currently supported if the Configuration Cache is enabled.

For builds scripts written in Groovy, the task fails because the method cannot be found.
The following snippet uses a top-level method in the `listFiles` task:

====
include::sample[dir="snippets/configurationCache/topLevel/groovy",files="build.gradle[tags=not-supported]"]
====

Running the task with the Configuration Cache enabled produces the following error:
----
include::{snippetsPath}/configurationCache/topLevel/tests-groovy/notSupported.out[]
----

To prevent the task from failing, convert the referenced top-level method to a static method within a class:
====
include::sample[dir="snippets/configurationCache/topLevel/groovy",files="build.gradle[tags=workaround]"]
====

Build scripts written in Kotlin cannot store tasks that reference top-level methods or variables at execution time in the Configuration Cache at all.
This limitation exists because the captured script object references cannot be serialized.
The first run of the Kotlin version of the `listFiles` task fails with the Configuration Cache problem.

====
include::sample[dir="snippets/configurationCache/topLevel/kotlin",files="build.gradle.kts[tags=not-supported]"]
====

To make the Kotlin version of this task compatible with the Configuration Cache, make the following changes:
====
include::sample[dir="snippets/configurationCache/topLevel/kotlin",files="build.gradle.kts[tags=workaround]"]
====
<1> Define the method inside an object.
<2> Define the variable in a smaller scope.

See link:{gradle-issues}22879[gradle/gradle#22879].

[[config_cache:not_yet_implemented:build_services_in_fingerprint]]
=== Using Build Services to Invalidate the Configuration Cache

Currently, it is impossible to use a `BuildServiceProvider` or provider derived from it with `map` or `flatMap` as a parameter for the `ValueSource`, if the value of the `ValueSource` is accessed at configuration time.
The same applies when such a `ValueSource` is obtained in a task that executes as part of the configuration phase, for example tasks of the `buildSrc` build or included builds contributing plugins.

Note that using a `@ServiceReference` or storing `BuildServiceProvider` in an `@Internal`-annotated property of a task is safe.

Generally speaking, this limitation makes it impossible to use a `BuildService` to invalidate the Configuration Cache.

See link:{gradle-issues}24085[gradle/gradle#24085].
