Skip to content

clean's doLast closes SpotlessCache classloaders that concurrently-running spotless tasks still hold (LINE_UNDEFINED NoClassDefFoundError/InvocationTargetException) #3067

Open

Description

@mafolab1

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/EditorConfigDefaults on one run and kotlin/collections/ArraysKt___ArraysJvmKt on 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.kts in "a very different place" is expected.
  • Switching versions appears to "reset whatever state", because a version change alters the JarState, hence the SerializedKey, hence which loaders exist — and it re-rolls task timing.
  • InvocationTargetException vs NoClassDefFoundError is 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:

  1. 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.
  2. Reference-count the loaders. close() when the last holder releases. Correct, but needs every FormatterStep consumer to release.
  3. Make the clean hook not fire mid-build. Registering the clear as a build-finished action rather than a doLast on each clean would keep the intent (a clean invalidates the cache) without closing loaders while tasks are running.
  4. At minimum, order it. Make every spotless* task mustRunAfter every clean, 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-lib 4.10.2) — the relevant code is byte-identical to main as of today
  • ktlint 1.8.0 (the step is irrelevant; spotless-lib 8.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

  1. jhnesk commented on Sep 23, 2026

    @jhnesk

    Here is a workaround that works for me. Essentially #4 of the suggested fixes.

    allprojects {
    	def cleanTasks = rootProject.allprojects.collect { it == rootProject ? ':clean' : "${it.path}:clean" }
    	tasks.withType(com.diffplug.gradle.spotless.SpotlessTask).configureEach {
    		mustRunAfter(cleanTasks)
    	}
    }
    
  2. nvervelle commented on Nov 5, 2026

    @nvervelle

    Additional data point, and why the "only the first clean clears" assumption does not hold on Gradle 9:

    Summary
    SpotlessPlugin registers clean.doLast { SpotlessCache.clearOnce(System.identityHashCode(project.getRootProject())) } on every project. SpotlessCache.clear() closes every cached FeatureClassLoader. Two things make it unsafe in current Gradle:

    1. The "only once per build" guard is defeated. On Gradle 9 (checked on 9.8.2), project.getRootProject() returns a per-project LifecycleAwareProject wrapper, so identityHashCode differs per project and every project's clean closes all loaders.
    2. With the configuration cache or --parallel, a clean of 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 class in JarState-based steps (seen with ktfmt: org/jetbrains/kotlinx/ktfmt/format/FileType, kotlin/collections/ArraysKt___ArraysKt, kotlinx/coroutines/NodeList). Any step that uses JarState.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=300 fails every time. It also fails with --no-configuration-cache --parallel, and passes with --no-configuration-cache alone. The sleep only makes the timing deterministic: in a real multi-project build a slow clean (large build/ dir) is enough, and we see about 50% failures.

    Stack trace

    java.lang.NoClassDefFoundError: org/jetbrains/kotlinx/ktfmt/format/FileType
      at com.diffplug.spotless.glue.ktfmt.KtfmtFormatterFunc.apply(KtfmtFormatterFunc.java:63)
      at com.diffplug.spotless.FormatterStepEqualityOnStateSerialization.format(FormatterStepEqualityOnStateSerialization.java:51)
      at com.diffplug.spotless.LintState.of(LintState.java:177)
      at com.diffplug.gradle.spotless.SpotlessTaskImpl.processInputFile(SpotlessTaskImpl.java:136)
    Caused by: java.lang.ClassNotFoundException: org.jetbrains.kotlinx.ktfmt.format.FileType
    

    Possible fixes

    • Key clearOnce on something that is really per build, for example the build invocation ID or a BuildService lifecycle, not the identity of the root project wrapper.
    • Do the clear at the start of the build, or in a build service, rather than in each clean task's doLast that can run concurrently with formatting.
    • Or make Spotless tasks mustRunAfter the clean tasks of the build.
    • Or don't 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

    val allCleans = rootProject.allprojects.map { p -> p.tasks.matching { it.name == "clean" } }
    tasks.withType<com.diffplug.gradle.spotless.SpotlessTask>().configureEach { mustRunAfter(allCleans) }

    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 .kt files in a. Project b delays its clean by 300 ms, so its Spotless doLast lands while a:spotlessKotlin is formatting.

    settings.gradle.kts

    pluginManagement { repositories { gradlePluginPortal() } }
    dependencyResolutionManagement { repositories { mavenCentral() } }
    rootProject.name = "spotless-clean-race"
    include("a", "b")

    build.gradle.kts

    plugins { 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).

    ./gradlew clean spotlessApply --configuration-cache -PcleanDelayMs=300

    Results (3–4 runs each):

    Command Result
    --configuration-cache, daemon or --no-daemon, delay 200/300 ms 16/16 fail
    --configuration-cache, delay 500 ms, daemon (a finishes first) 0/4 fail
    --no-configuration-cache 0/3 fail
    --no-configuration-cache --parallel 3/3 fail
    Spotless 8.11.0 3/3 fail
    With the mustRunAfter workaround 0/3 fail

    Failure:

    Execution failed for task ':a:spotlessKotlinApply'.
    > There were 20 lint error(s), they must be fixed or suppressed.
      src/A1.kt:LINE_UNDEFINED ktfmt(java.lang.NoClassDefFoundError) kotlinx/coroutines/NodeList (...)
    
  3. kabrana commented on Nov 13, 2026

    @kabrana

    Another data point: Spotless 8.9.0, Gradle 9.7.1, multi-project Java build, --parallel with clean in the same invocation. removeUnusedImports failed with LINE_UNDEFINED … NoClassDefFoundError: com/google/common/collect/ImmutableList across one project's files. One more consequence worth noting: the lint from the thrown step is part of spotlessJava's output, so with the build cache on, the following build restored the task FROM-CACHE and failed the same way until the cache entry was deleted. On the workaround: listing clean task paths ("<path>:clean") instead of tasks.matching { it.name == 'clean' } or tasks.named { … } keeps task configuration lazy. In our build the filter versions created ~4,300 tasks versus ~170.

  4. dromero001 commented on Nov 14, 2026

    @dromero001

    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 build fails in spotlessJava in some module with NoClassDefFoundError for 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:

    • Warm daemon with --no-build-cache: 5 of 6 clean build runs failed.
    • Fresh daemon: about 1 in 8.
    • With the build cache on, the race was hidden (6 of 6 green), because the Spotless tasks were restored from the cache instead of running.
    • --max-workers=1, or clean and build as two separate invocations: never.

    Workaround (Kotlin DSL, in a convention plugin applied to every module):

    val cleanTaskPaths =
        gradle.rootProject.allprojects.filter { it.buildFile.exists() }.map { "${it.path.trimEnd(':')}:clean" }
    tasks.withType<com.diffplug.gradle.spotless.SpotlessTask>().configureEach {
        mustRunAfter(cleanTaskPaths)
    }

    The buildFile.exists() filter skips container projects such as :adapters, which have no clean task. Task paths are strings rather than tasks.matching { … }, so the configuration cache still works, as noted above.

    Result: 0 failures in 10 warm-daemon clean build runs plus 2 fresh-daemon runs (--no-build-cache). The configuration cache is still reused on the next build.

  5. i23098 commented on Nov 16, 2026

    @i23098

    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 clearOnce the same key: @nvervelle is right, and our earlier comment on #2850 was wrong (now corrected there). Called from a plugin's apply(Project), as SpotlessPlugin does, project.getRootProject() in a subproject returns a new LifecycleAwareProject wrapper on every call. That holds with the configuration cache on and off. Only the root project gets the same object each time:

    :        key=245693460  again=245693460  type=DefaultProject_Decorated
    :model   key=2145754463 again=480588847  type=LifecycleAwareProject_Decorated
    :server  key=285892093  again=1618714983 type=LifecycleAwareProject_Decorated
    

    So every project's clean closes every loader, and the last clean to 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 clean back 1.5 s. With that, ./gradlew clean spotlessCheck failed 3 times out of 3, in ktlint's checks of every project. The lints were NoClassDefFoundError for com/pinterest/ktlint/rule/engine/api/EditorConfigDefaults, or A non-empty set of 'ruleProviders' need to be provided, which is what you get when ktlint's ServiceLoader finds nothing through a closed loader. Each failed task had started before that clean ended.

    The mustRunAfter workaround fixes it: with every SpotlessTask ordered after every clean, the same runs passed 7 times out of 7, with clean held 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:

    val everyClean = rootProject.allprojects.map { other -> other.tasks.named { it == "clean" } }
    tasks.withType<SpotlessTask>().configureEach {
        mustRunAfter(everyClean)
    }

    Since getRootProject() no longer returns the same object, keying clearOnce on 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions