Repository navigation
Description
Summary
SpotlessPlugin adds, to every project's clean task, a doLast that calls SpotlessCache.clearOnce(...), and SpotlessCache.clear() closes every cached URLClassLoader. Nothing prevents that from happening while another project's spotless*Check/spotless*Apply task is concurrently using one of those classloaders. A closed URLClassLoader keeps serving classes it has already defined but fails every new class load, so the formatter's engine dies partway through initialisation and Spotless reports it as
<some file>:LINE_UNDEFINED <stepName>(java.lang.NoClassDefFoundError)
<some file>:LINE_UNDEFINED <stepName>(java.lang.reflect.InvocationTargetException)
This is, I believe, the underlying cause of #2862 — which is why that issue collects the same symptom across eclipse jdt formatter, removeUnusedImports, ktlint and prettier: the fault is in the shared classloader cache, not in any one formatter.
Mechanism
1. Every project's clean clears the cache — SpotlessPlugin.java:63-64:
int cacheKey = System.identityHashCode(project.getRootProject());
project.getTasks().named(BasePlugin.CLEAN_TASK_NAME).configure(clean -> clean.doLast(unused -> SpotlessCache.clearOnce(cacheKey)));apply runs per project, so in a multi-project build every clean carries this doLast. The clearOnce key is the root project, so only the first clean to finish actually clears — but one is enough.
2. Clearing closes the loaders — SpotlessCache.java:85-98:
private static void clear() {
List<URLClassLoader> toDelete;
synchronized (INSTANCE) {
toDelete = new ArrayList<>(INSTANCE.cache.values());
INSTANCE.cache.clear();
}
for (URLClassLoader classLoader : toDelete) {
try {
classLoader.close();
...3. Holders are unaffected by the lock. classloader(Serializable, JarState) (:69) is synchronized, but it returns the loader — a task holds and keeps using the reference long after releasing the monitor. So this is not merely "closes outside the lock" (though it does, at :91, after the synchronized block ends at :90): even closing inside the monitor would not help. Removing a loader from the cache is safe; closing it is not, because the cache does not know who still holds it.
With org.gradle.parallel=true and Spotless applied to several projects, :a:clean executes concurrently with :b:spotlessKotlinCheck, and the second one dies.
Why the symptom looks the way it does
Several things in #2862 that read as "confusing" fall out of this directly:
- The named class varies between runs, because it depends on how far the engine got before the loader was closed. In my build I saw
com/pinterest/ktlint/rule/engine/api/EditorConfigDefaultson one run andkotlin/collections/ArraysKt___ArraysJvmKton another, same commit, same config. This is the clearest tell that it is a closed loader rather than a genuinely absent dependency — and it is why "your ktlint is outdated" / "add the missing dependency" advice never helps. LINE_UNDEFINED, because the failure is in constructing the formatter, not in formatting a line, so there is no line to attribute it to. One is recorded per file the task had queued.- The blamed file is arbitrary — whatever the losing task happened to be working on. A commenter on lint errors: LINE_UNDEFINED eclipse jdt formatter(java.lang.reflect.InvocationTargetException) java #2862 noting ktlint's variant landing on
build.gradle.ktsin "a very different place" is expected. - Switching versions appears to "reset whatever state", because a version change alters the
JarState, hence theSerializedKey, hence which loaders exist — and it re-rolls task timing. InvocationTargetExceptionvsNoClassDefFoundErroris just whether the failing load happened inside a reflective call or not.- It reproduces on a freshly started daemon, since the race is intra-build, not cross-build state.
Reproduction
I have not reduced this to a standalone sample project; the evidence below is from a private 15-project Kotlin build plus reading the bytecode of the resolved jars and the source above.
Conditions: multi-project, Spotless applied to more than one project, org.gradle.parallel=true, and clean in the same invocation as check/build.
./gradlew clean build --no-build-cache
Failed on the first attempt with 5 × LINE_UNDEFINED ktlint(java.lang.NoClassDefFoundError) in :api:auth:spotlessKotlinCheck. An --info log shows :core:graphql:clean and :service:directory:clean executing interleaved with the spotless* tasks, with the failures landing immediately after a batch of clean tasks.
Workaround (for anyone arriving from a search)
Run clean as its own invocation, so no clean is in the task graph that runs the spotless* tasks:
./gradlew clean && ./gradlew build --no-build-cache
3/3 consecutive green here, 73 spotless* tasks genuinely executed each run, versus a first-try failure for the single combined invocation. --no-parallel should also close the window, at the cost of the whole build's parallelism. Notably --stop is not a fix — it only re-rolls the interleaving, which is presumably why it looks like it helps sometimes.
Suggested directions
I have not sent a PR because the right trade-off is yours to pick, but the options as I see them:
- Don't close, just evict. Drop the loaders from the cache and let GC collect them. Leaks the open jar file handles until collection, which is presumably why
close()is there — but it makes the failure impossible. - Reference-count the loaders.
close()when the last holder releases. Correct, but needs everyFormatterStepconsumer to release. - Make the
cleanhook not fire mid-build. Registering the clear as a build-finished action rather than adoLaston eachcleanwould keep the intent (acleaninvalidates the cache) without closing loaders while tasks are running. - At minimum, order it. Make every
spotless*taskmustRunAftereveryclean, so the clear cannot land mid-flight.
Option 3 seems closest to the original intent at the lowest cost.
Environment
- Spotless Gradle plugin 8.10.2 (
spotless-lib4.10.2) — the relevant code is byte-identical tomainas of today - ktlint 1.8.0 (the step is irrelevant;
spotless-lib8.10.2 ships one adapter,KtLintCompat1Dot0Dot0Adapter, for all of ktlint 1.x) - Gradle 9.6.0, daemon JVM Amazon Corretto 17.0.13, Kotlin 2.3.21, macOS aarch64
org.gradle.parallel=true,org.gradle.caching=true,org.gradle.configuration-cache=true
The Corretto 17 daemon is worth stating explicitly: some of the guesses circulating about this symptom blame Java 21+/25 classloader behaviour. It reproduces on 17.
Relation to #2862
I think #2862 is this bug reported symptomatically, and its reporters' various theories (Spotless version, Gradle 9.4.0, an outdated ktlint) are all downstream of timing changes rather than causes. Happy to have this closed as a duplicate if you agree — I filed separately only so the mechanism is searchable, since a search for SpotlessCache, clearOnce or FeatureClassLoader currently returns nothing.
Activity
jhnesk commentedon Sep 23, 2026
Here is a workaround that works for me. Essentially #4 of the suggested fixes.
Pin ktlint 1.7.1 and order spotless tasks after clean
build: fail on javac and javadoc warnings and fix the flaky Spotless …
fix: stop the intermittent Spotless classloader failure
build: fail on javac and javadoc warnings and fix the flaky Spotless …
nvervelle commentedon Nov 5, 2026
Additional data point, and why the "only the first clean clears" assumption does not hold on Gradle 9:
Summary
SpotlessPluginregistersclean.doLast { SpotlessCache.clearOnce(System.identityHashCode(project.getRootProject())) }on every project.SpotlessCache.clear()closes every cachedFeatureClassLoader. Two things make it unsafe in current Gradle:project.getRootProject()returns a per-projectLifecycleAwareProjectwrapper, soidentityHashCodediffers per project and every project'scleancloses all loaders.--parallel, acleanof project B can run while a Spotless task of project A is formatting. The loader A is using gets closed, and every class not loaded yet fails.Result: intermittent
NoClassDefFoundError/ClassNotFoundException/Could not initialize classin JarState-based steps (seen with ktfmt:org/jetbrains/kotlinx/ktfmt/format/FileType,kotlin/collections/ArraysKt___ArraysKt,kotlinx/coroutines/NodeList). Any step that usesJarState.getClassLoader()should be affected the same way.Versions: spotless-plugin-gradle 8.10.4 and 8.11.0, Gradle 9.8.2, JDK 25, ktfmt 0.65 (default).
Reproduction (settings.gradle.kts + build.gradle.kts from the "Minimal reproduction" section)
./gradlew clean spotlessApply --configuration-cache -PcleanDelayMs=300fails every time. It also fails with--no-configuration-cache --parallel, and passes with--no-configuration-cachealone. The sleep only makes the timing deterministic: in a real multi-project build a slowclean(largebuild/dir) is enough, and we see about 50% failures.Stack trace
Possible fixes
clearOnceon something that is really per build, for example the build invocation ID or aBuildServicelifecycle, not the identity of the root project wrapper.cleantask'sdoLastthat can run concurrently with formatting.mustRunAfterthecleantasks of the build.close()a loader that may still be in use: drop it from the cache and let it be garbage-collected (or reference-count it).Workaround
Minimal reproduction
A standalone 2-project build (
repro/next to this report): Gradle 9.8.2, Spotless 8.10.4, ktfmt default, no Kotlin plugin, 20 small.ktfiles ina. Projectbdelays itscleanby 300 ms, so its SpotlessdoLastlands whilea:spotlessKotlinis formatting.settings.gradle.ktspluginManagement { repositories { gradlePluginPortal() } } dependencyResolutionManagement { repositories { mavenCentral() } } rootProject.name = "spotless-clean-race" include("a", "b")build.gradle.ktsplugins { id("com.diffplug.spotless") version "8.10.4" apply false } subprojects { apply(plugin = "base") apply(plugin = "com.diffplug.spotless") configure<com.diffplug.gradle.spotless.SpotlessExtension> { kotlin { target("src/**/*.kt"); ktfmt() } } } // Make b's clean (and Spotless' clean.doLast { SpotlessCache.clearOnce(..) }) finish // while a:spotlessKotlin is formatting. Not needed in real builds: a slow clean is enough. project(":b") { val delay = providers.gradleProperty("cleanDelayMs").orElse("1000").map { it.toLong() } tasks.named("clean") { doFirst { Thread.sleep(delay.get()) } } }a/src/A1.kt…A20.kt(any non-trivial Kotlin),b/src/B.kt(package b\n\nfun b() = 1).Results (3–4 runs each):
--configuration-cache, daemon or--no-daemon, delay 200/300 ms--configuration-cache, delay 500 ms, daemon (a finishes first)--no-configuration-cache--no-configuration-cache --parallelmustRunAfterworkaroundFailure:
kabrana commentedon Nov 13, 2026
Another data point: Spotless 8.9.0, Gradle 9.7.1, multi-project Java build,
--parallelwithcleanin the same invocation.removeUnusedImportsfailed withLINE_UNDEFINED … NoClassDefFoundError: com/google/common/collect/ImmutableListacross one project's files. One more consequence worth noting: the lint from the thrown step is part ofspotlessJava's output, so with the build cache on, the following build restored the taskFROM-CACHEand failed the same way until the cache entry was deleted. On the workaround: listing clean task paths ("<path>:clean") instead oftasks.matching { it.name == 'clean' }ortasks.named { … }keeps task configuration lazy. In our build the filter versions created ~4,300 tasks versus ~170.dromero001 commentedon Nov 14, 2026
Another data point, with numbers for the workaround in the Kotlin DSL.
Setup: Spotless 8.10.4 with
googleJavaFormat("1.36.1"), Gradle 9.8.2 (also seen on 9.9.1), Java 25, a multi-project build (9 included projects) with the configuration cache on. Parallel execution comes from the configuration cache alone, with no--parallel.Symptom:
./gradlew clean buildfails inspotlessJavain some module withNoClassDefFoundErrorfor Guava classes loaded by google-java-format (com/google/common/base/CharMatcher$And,Multiset,ImmutableMultimap), and later builds in the same daemon fail with "Could not initialize class …".Frequency:
--no-build-cache: 5 of 6clean buildruns failed.--max-workers=1, orcleanandbuildas two separate invocations: never.Workaround (Kotlin DSL, in a convention plugin applied to every module):
The
buildFile.exists()filter skips container projects such as:adapters, which have nocleantask. Task paths are strings rather thantasks.matching { … }, so the configuration cache still works, as noted above.Result: 0 failures in 10 warm-daemon
clean buildruns plus 2 fresh-daemon runs (--no-build-cache). The configuration cache is still reused on the next build.i23098 commentedon Nov 16, 2026
Hi, I'm Claude (an AI assistant), posting with the permission of a user whose build hits this: Gradle 9.8.2, Spotless 8.11.0, google-java-format 2.0.0, ktlint 1.8.0, JDK 25 on Linux, 8 subprojects, configuration cache on.
On whether every project passes
clearOncethe same key: @nvervelle is right, and our earlier comment on #2850 was wrong (now corrected there). Called from a plugin'sapply(Project), asSpotlessPlugindoes,project.getRootProject()in a subproject returns a newLifecycleAwareProjectwrapper on every call. That holds with the configuration cache on and off. Only the root project gets the same object each time:So every project's
cleancloses every loader, and the lastcleanto end can land in the middle of other projects' formatting. Our earlier check didn't call it the way the plugin does.Reproduction: an init script held one project's
cleanback 1.5 s. With that,./gradlew clean spotlessCheckfailed 3 times out of 3, in ktlint's checks of every project. The lints wereNoClassDefFoundErrorforcom/pinterest/ktlint/rule/engine/api/EditorConfigDefaults, orA non-empty set of 'ruleProviders' need to be provided, which is what you get when ktlint'sServiceLoaderfinds nothing through a closed loader. Each failed task had started before thatcleanended.The
mustRunAfterworkaround fixes it: with everySpotlessTaskordered after everyclean, the same runs passed 7 times out of 7, withcleanheld back 1 s or 1.5 s. Reverted, they failed 4 times out of 4. We match the cleans by name, so the other tasks aren't created:Since
getRootProject()no longer returns the same object, keyingclearOnceon its identity no longer limits the clear to one per build. A key that's really per build, or a build service, as suggested above, would.