Hi! I have a question about coroutines and thread ...
# coroutines
r
Hi! I have a question about coroutines and thread confinement. Is it possible to keep a coroutine running strictly on the same thread? I know it might sound obvious, but I just want to confirm my understanding. Context: Some time ago I was experimenting with porting *Hibernate Reactive (
CompletionStage
)* to Kotlin coroutines. Hibernate Reactive requires that all operations run on the same thread where the session and the database connection (Vert.x SQL event loop) were created. My idea was to create some sort of internal thread/dispatcher pool to store the dispatcher used to open the connection and session and then use the same dispatcher when awaiting (using extension functions that convert
CompletableFuture
to suspending operations). However, it didn’t work, coroutines kept jumping between threads. I also tried using the Vert.x coroutine dispatcher, which seems to propagate the event-loop context correctly, but that still doesn’t guarantee staying on the same physical thread, which HR seems to require. Additionally, HR needs that sessions (and nested transactions) are shared across coroutine calls, so I would need to reuse the dispatcher of an already opened session. I’m thinking this might require a custom
CoroutineContext
element for transaction/session propagation, similar to how Exposed handles it. Am I on the right track? So is there any reliable way to enforce strict single-thread execution for coroutines, similar to Vert.x event loop confinement, but without thread hopping? Or is this simply not how coroutines are intended to operate? Thanks!
s
Yeah, even when using
Dispatcher#limitedParallelism(1, ...)
won't guarantee that the same thread is used. However, on the JVM you can create an Executor Service with only one single thread and create a Dispatcher from that. That will guarantee your coroutines, using that dispatcher, will all run on that one thread.
o
r
Does this prevent them from deadlocking themselves? This happened to me a lot with nested and suspend lambda.
o
It's on a single thread. If one coroutine contains blocking code, it will block everything else on that thread.
r
Interesting, now I don't know if I was doing things wrong or if Vertex SQL or Hibernate are using something thread-blocking, which they shouldn't be... interesting
z
you can deadlock even if everything is fully suspending, completely preventing deadlocks is not a problem kotlin solves at the language level
👌 1