15

Structured concurrency: will Java Loom beat Kotlin’s coroutines?

 2 years ago
source link: https://xebia.com/structured-concurrency-will-java-loom-beat-kotlins-coroutines/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Kotlin and Java Loom: structured concurrency for the masses

Java, as slow adopter of new concepts is getting structured concurrency as part of the Loom project. This addition enables native support for coroutines (termed virtual threads) in Java. What does that mean for Java & Kotlin developers? Should we now all transform our existing code bases to support virtual threads? Or even jump back to Java? We compare two approaches to do structured concurrency on the JVM: Java Loom’s virtual threads and Kotlin’s coroutines. As it turns out, Kotlin coroutines show to be more developer friendly, while Java Loom might have its sweet spot as part of Java libraries and frameworks. Want to know why? Buckle up, as we have a lot to talk about!

My colleague and Kotlin specialist Urs Peter suggested to look into Loom and compare it to Kotlin coroutines. We did that on one of our (awesome, I might add) innovation days

There we realised that Java is not only a programming language, but also a platform. Actually you could see it the other way around. The Java programming language is the reference implementation for the Java platform. This is breaking news, because this concept gives you the opportunity to hate Java in two different ways…

Haha, just joking. But all jokes aside, this split view on Java puts Loom in the position of one of the most impactful Java projects. But also one of the most silent ones. Loom extends the JVM with structured concurrency with only minor changes to the programming language. So what is Loom exactly and what does it have to do with Kotlin?

loom-virtual-threads-1024x492.pngKotlin coroutines
kotlin-coroutines-1024x492.pngLoom virtual threads
Hello world 2
Hello world 1
coroutineScope { // <---- only needed on top-level
    launch {
        delay(500)
        println("Hello world 1")
    }
    println("Hello world 2")
}

The structured concurrency constructs of Kotlin map in most cases “more or less” to the Java-Loom constructs:

coroutineScope ~ try (ExecutorService exs = Executors.newVirtualThreadExecutor())
launch -> exs.submit(...)
async & await -> Future<...> f = exs.submit(...) & f.join()
sadfasdf
<?php
  echo "Hi, I'm a PHP script!";
?>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK