https://kotlinlang.org logo
Title
b

bogdoll

03/05/2022, 1:40 PM
I have some legacy business logic which I would like to refactor to use coroutines. I have one central datastructure which is currently protected by a synchronous block. I could replace the synchronous block also with a mutex. But both mutex and synchronous blocks are not compatible with coroutines, or? So what would be the coroutine way to access a datastructure which should not be accessed in a multithreaded way.
j

Joffrey

03/05/2022, 2:02 PM
You can use a suspending
Mutex
provided in the coroutines library: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/
In general, it's easier if you can avoid shared mutable state, but if you have to (or if you want to migrate to coroutines without changing the architecture),
Mutex
is fine
One way to avoid shared mutable state is to have a single coroutine that owns the data structure and receives events to change it via channels (actor pattern)
👍 1
b

bogdoll

03/05/2022, 6:36 PM
Do you have an easy example of that? Basically how would somebody who messages the actor to do something wait for the answer? I also just saw that that the actor class is marked with @ObsoleteCoroutinesApi. This sounds as this class should not be used anymore.
j

Joffrey

03/05/2022, 7:22 PM
If you want to wait for the answer anyway, I think you might as well use a mutex. I was mentioning the actor as a pattern but not necessarily using the specific built-in api that's deprecated (or maybe experimental)