Java Virtual Threads vs Kotlin Coroutines: Suspension Models and the Shifting Bottleneck
The usage and internals of Java virtual threads and Kotlin coroutines are already widely covered. Rather than explaining each technology separately, this post compares how their different ways of implementing suspension change how code is written and operated. It is written for JVM server developers who have adopted or are evaluating virtual threads, and it focuses on where the costs that virtual…
Java virtual threads and Kotlin coroutines are two methods to handle suspension in JVM server development, both aiming to improve code readability and resource efficiency. However, they achieve this goal through different suspension models.
In Java virtual threads, suspension and resumption are managed by saving the stack and unmounting from the carrier, which is an OS thread. This allows the thread to return to the original OS thread without any marker in the code. For instance, in the provided code snippet, the `for` loop runs each task on its own virtual thread, which can efficiently handle operations like fetching data from a database without blocking the OS thread.
On the other hand, Kotlin coroutines handle suspension by calling the function again after saving local variables and the next label value in a Continuation object. This makes suspension points explicit in the source code, requiring the use of `suspend` and `launch` keywords. While coroutines also release the thread while waiting, the function has to be explicitly declared as `suspend`, and the suspension point is marked in the code.
In both cases, the key difference lies in how the suspended state is kept. Virtual threads keep it by saving the stack, while coroutines do it by returning from the function and calling it again later. Despite these differences, neither approach increases the total amount of resources; they merely shift the bottleneck to a less visible place. The resource bottleneck doesn't disappear, it just moves to a more hidden location.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.