How do you mix coroutines and Java Virtual Threads...
# coroutines
b
How do you mix coroutines and Java Virtual Threads? I know that I can use suspend controller methods in spring boot but how does a Java application consume coroutines, e.g. when using an API client with coroutines written in Kotlin (I suspect mixing coroutines with Reactive Spring Boot is simpler)
✅ 1
c
Java cannot call a
suspend
function, so you will need a 'bridge' method on the Kotlin side. In Kotlin, you can use
future { …your code… }
to create a
CompletableFuture
that a Java virtual thread can block on.
b
I see, thank you
w
I just want to make sure that people don't reach out to
future
too eagerly. The main purpose of both kotlinx.coroutines as well as virtual threads, is to get rid of asynchronous functions (AKA, a function that schedules work, and returns before that work might be done). And
future
is one such example. It's slightly better than your usual asynchronous functions because it takes a
CoroutineScope
, but it's not as nice as structured concurrency. The problems with using this pattern is that: • If your vthread gets canceled, the future doesn't get canceled by default. • Your `ScopedValue`s aren't passed down to the underlying coroutine. • It's unclear from the outside where exceptions go if you don't await the result. • It's unclear where the
CoroutineContext
comes from. These are answers that structured concurrency answers. Ideally, you could simply use
runBlocking
, which answers 3/4 questions. However, it sadly also has serious footguns, but it probably has less footguns than not using structured concurrency at all with `future`s. I just think that this nuance is important when giving recommendations on this topic.
👁️ 1
v
Thanks, that makes sense. In my case, the Java entry point is called on the main thread, and I can’t refactor it to be
suspend
or use
runBlocking
. I was looking at
CompletableFuture
, but based on your concerns around structured concurrency, what would you recommend for this kind of Java-to-suspend bridge?
w
It sounds like in your situation, you cannot feasibly preserve structured concurrency. Meaning you will need to introduce asynchronous functions, which also introduces the list of problems I talked about. (if you're curious about why I keep saying asynchronous functions are so bad, you can watch

this starting from 9:55▾

). The best way to do that depends on your use case, but the simplest way would be
future
or
launch
depending on whether you want to process the result in Java.
👍 1