Toolchains and sourceCompatibility

Two questions are easy to mix up. Which JDK compiles the code, and which Java version the compiled code targets. The first is a toolchain, the second is a release, and a build that answers both is reproducible on a machine with three JDKs installed.

What Gradle found

settings.gradle

rootProject.name = 'shop'

build.gradle

plugins { id 'java' } java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }

With no toolchain block Gradle compiles with the JVM that runs the build. With one it looks for an installation of that version, and gradle javaToolchains prints what it found:

gradle -q javaToolchains --console=plain --offline --no-daemon

+ Options
    | Auto-detection: Enabled
    | Auto-download: Enabled

+ Alpine JDK 21 (21.0.13.1+2-alpine-r0)
    | Location: /usr/lib/jvm/java-21-openjdk
    | Language Version: 21
    | Vendor: Alpine
    | Architecture: amd64
    | Is JDK: true
    | Detected by: Current JVM

A toolchain in the build

The block above is the whole configuration. Gradle searches the usual folders of the system, the JAVA_HOME of the moment and any path listed in org.gradle.java.installations.paths in gradle.properties. When the version is missing the build fails with a message that lists the installations it did find, instead of silently compiling with another JDK.

A toolchain does not download anything by itself. A build that should fetch a missing JDK applies the Foojay resolver plugin in the settings file, which needs a network: this image has none, and the errors lesson shows what the generated java-application build says about it when the plugin is not cached.

The other way: release

A toolchain picks the JDK; the release picks the class file version the compiler writes. options.release = 17 on the compile tasks compiles with the JDK of the build and produces classes a Java 17 runtime can load, and it checks the API of Java 17 at the same time. The older pair sourceCompatibility and targetCompatibility only sets the language level and the class file version, so a call to an API that Java 17 does not have compiles and fails at run time.

The next lesson configures the compile tasks, options.release included, and shows the warnings the compiler prints.

Related

Article author: Arthur Isaev

Banner image