- Download JDK 20 EA (Early Access) build from https://jdk.java.net/20/ and unzip it to a local folder.
- 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")
}
- 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
- On Intellij/File/Project Structure,
- Set the SDK with the downloaded EA SDK.
- Set language level to "X - Experimental Features"
- 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())
}
}