Running and Building Gradle with Different JDKs - Sip of Java

If you are using Gradle as the build tool for your projects and want to work with the latest JDK releases or early-access builds, you might think you are stuck until Gradle supports those versions of the JDK, which might take a few months. However, that’s not the case, and we will explore in this article how to run Gradle with one JDK version while building and testing with a different JDK version.

Managing Multiple JDKs

When working with multiple JDKs, using a tool like SDKMan or Jenv (for macOS) is highly recommended. These tools enable you to easily manage and switch between your local JDKs. This article assumes that you have multiple JDKs installed on your system: one for running Gradle, and the other for executing the tasks in the build. Be sure that the JDK installed to run Gradle is supported by Gradle. As of the time of this article, the latest Gradle version is 7.6 which supports JDK 19.

Configuring the Toolchain

By default, Gradle will use the JDK that is being used to run Gradle itself to execute the tasks in the build. This can be easily changed by configuring your toolchain. In the example below, Gradle will use JDK 20 to execute the tasks in the build regardless of the JDK version being used to run Gradle.

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(20))
    }
}

There are a few default behaviors Gradle uses to find a JDK install. Depending on your OS and if you have a JDK manager installed, Gradle will check certain places on your system to see if it can find the requested JDK version. If it is unable to find the requested JDK version, Gradle will attempt to download the requested JDK version. Be sure to check the Toolchains link under the Additional Reading section which provides the full explanation of this lookup process.

Setting JDK Version with Properties

Gradle’s default behavior for looking up a JDK version can be disabled through properties if it doesn’t match your needs. This can be helpful if you are working with multiple JDKs of the same version or running builds on a shared system.

To disable the auto-detection of a JDK, set the org.gradle.java.installations.auto-detect property to false like below:

org.gradle.java.installations.auto-detect=false

To disable the auto-downloading of a JDK, set the org.gradle.java.installations.auto-download property to false like below:

org.gradle.java.installations.auto-download=false

Finally, you can configure Gradle to look in a specific location for a JDK by providing it with an environment property, like in this example below:

org.gradle.java.installations.fromEnv=JAVA20_HOME

Additional Reading

Toolchains for JVM projects

Gradle Compatibility Matrix

Using Java feature previews with Gradle

Hat tip to: Cedric Champeau for help with this Sip of Java

Happy coding!