Skip to content

Instantly share code, notes, and snippets.

@pmhsfelix
Last active December 30, 2022 13:09
Show Gist options
  • Save pmhsfelix/25eb74684d39992bd7164a00ca4ee6f5 to your computer and use it in GitHub Desktop.
Save pmhsfelix/25eb74684d39992bd7164a00ca4ee6f5 to your computer and use it in GitHub Desktop.
Trying out JDK 20 EA with gradle, kotlin, and IntelliJ
  1. Download JDK 20 EA (Early Access) build from https://jdk.java.net/20/ and unzip it to a local folder.
  2. On build.gradle.kts, add
// to use JDK 20 for the build and execution
java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(20))
    }
}

// to enable preview features, such as virtual threads when compiling, testing, or launching an application.
tasks.withType<JavaCompile> {
    options.compilerArgs.add("--enable-preview")
}

tasks.withType<Test> {
    jvmArgs("--enable-preview", "--add-modules", "jdk.incubator.concurrent")
}

tasks.withType<JavaExec> {
    jvmArgs("--enable-preview", "--add-modules", "jdk.incubator.concurrent")
}

  1. On gradle.properties, add
org.gradle.java.installations.paths=<path to downloaded JDK 20 EA>/Contents/Home
org.gradle.java.installations.auto-download=false
org.gradle.java.installations.auto-detect=false

  1. On Intellij/File/Project Structure,
  • Set the SDK with the downloaded EA SDK.
  • Set language level to "X - Experimental Features"
  1. On Intellij/Preferences/Build, Execution, Deployment/Build tools/Gradle
  • Make sure the "Gradle JVM" is one supported by Gradle (e.g. JDK 17) and not the JDK 20 EA.

Use this little test function to assert virtual threads can be used.

    @Test
    fun `can use virtual threads`() {
        Executors.newVirtualThreadPerTaskExecutor().use { executor ->
            val res: Future<Boolean> = executor.submit<Boolean> {
                Thread.currentThread().isVirtual
            }
            assertTrue(res.get())
        }
    }

Use this little test to assert structured concurrency can be used.

    @Test
    fun `can use structured concurrency`() {
        StructuredTaskScope.ShutdownOnFailure().use { scope ->

            val f1 = scope.fork {
                Thread.sleep(Duration.ofSeconds(1))
                "hello"
            }
            val f2 = scope.fork {
                Thread.sleep(Duration.ofSeconds(1))
                " world"
            }
            scope.join()
            scope.throwIfFailed()

            assertEquals("hello world", f1.resultNow() + f2.resultNow())
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment