Jacoco & Gradle Test Kit with Java

Actually, it just failed naturally.
If your tests started 5 daemons, those 5 daemons try to get the write lock, and the task doLast { ... } tries to get the read lock.
Nothing guarantees that the write locks are granted first, so while reduced, it still happens that the file is not accessible as it is currently written to by one of the daemons.
So I now changed it a bit.
I still request the read lock on the file to be extra sure, but I changed the agent string to

org.gradle.jvmargs = -javaagent:$jacocoAgentJar=destfile=$jacocoDestfile,append=true,dumponexit=false,jmx=true

And then in the settings script of the projects under test I always add

import java.lang.management.ManagementFactory
import javax.management.ObjectName

abstract class JacocoDumper : BuildService<BuildServiceParameters.None>, AutoCloseable {
    override fun close() {
        val mBeanServer = ManagementFactory.getPlatformMBeanServer()
        val jacocoObjectName = ObjectName.getInstance("org.jacoco:type=Runtime")
        if (mBeanServer.isRegistered(jacocoObjectName)) {
            mBeanServer.invoke(jacocoObjectName, "dump", arrayOf(true), arrayOf("boolean"))
        }
    }
}
val jacocoDumper = gradle.sharedServices.registerIfAbsent("jacocoDumper", JacocoDumper::class) {}
jacocoDumper.get()
gradle.allprojects {
    tasks.configureEach {
        usesService(jacocoDumper)
    }
}

Now the writing of the JaCoCo data is done at the end of the build still within the SUT build run, so definitely before the file is then accessed by the outer build.
I think this should workout better.