Running Multiple JDK Versions with the Gradle Toolchains Configuration

Featured image for sharing metadata for article

When working with Java projects, you may end up working across multiple JDKs. It may be that you use different vendors, such as Oracle or the OpenJDK, or whether you're working with different Java versions.

It can be annoying to constantly change your JAVA_HOME, and doesn't work when you may need multiple JDKs in a single project.

Similar to the Maven Toolchains Plugin, from Gradle 6.7 there is toolchains support.

This allows you, in your build.gradle to add:

plugins {
  id 'java'

java {
  // NOTE: this is very important to make sure it's applied alongside any other
  // `java` configuration, such as `javadoc`
  toolchain {
    // if you're not yet on a newer JDK
    // or if you're using a newer JDK

The Toolchains for JVM projects documentation displays more information, such as specifying a vendor's JDK.

This is super helpful, and unlike the Maven configuration, Gradle does a bit more behind the scenes for us to detect what JDKs are available, and if any are missing, it'll attempt to download them!

You can see what Gradle autodetects using gradle -q javaToolchains:

$ gradle -q javaToolchains
 + Options
     | Auto-detection:     Enabled
     | Auto-download:      Enabled

 + OpenJDK 1.8.0_292
     | Location:           /usr/lib/jvm/java-8-openjdk
     | Language Version:   8
     | Vendor:             Oracle
     | Is JDK:             true
     | Detected by:        Current JVM

 + OpenJDK 11.0.11
     | Location:           /usr/lib/jvm/java-11-openjdk
     | Language Version:   11
     | Vendor:             Oracle
     | Is JDK:             true
     | Detected by:        Common Linux Locations

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #java #gradle.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.