https://kotlinlang.org logo
#coroutines
Title
# coroutines
e

Erik

04/23/2021, 2:41 PM
I have a function like:
@Synchronized fun foo()
that now is being refactored to be
@Synchronized suspend fun foo()
(ℹ️ this is
kotlin.jvm.Synchronized
). The synchronisation is still needed if I don't know the context in which this will be called, right? Is there a way to also get rid of the synchronisation? Can I change to a single threaded executor to ensure calls to this function happen sequentially? Or would I need a mutex? Or is it fine as-is? I'm asking because
@Synchronized suspend fun foo()
looks a bit non-coroutinesque to me.
m

mkrussel

04/23/2021, 2:52 PM
Synchronized will not work. You could use a mutex, but that changes the thread safety contract of that class. Would need to explore how it is being used. Before you exposed your synchronization scheme by making
this
be your lock. Also any other code in the class will need to use the mutex if they were synchronized before. They will then need to be
suspended
. The making access to it single threaded is a good option if possible. Other option is try to make it not deal with shared state. Trying to create a more functional programming style solution. Send immutable input and get immutable output. What solution works best depends on the problem being solved.
e

ephemient

04/23/2021, 2:58 PM
@kotlin.jvm.Synchronized
doesn't work on
suspend fun
- it wouldn't make sense to, as that flags the JVM to take a monitor with the function entry and exit, but as far as the JVM is concerned a
suspend fun
enters and exits at every suspend point
e

Erik

04/23/2021, 3:01 PM
Gee, am I glad that I asked!
Thanks for the responses
If I'd make a single threaded executor coroutine context, will that guarantee the correct execution order? Say I have 2 synchronised functions that I refactor to use the same single threaded context: what happens when fun A is called, then fun B? Does fun B suspend immediately? And what happens if then fun A suspends halfway through, does fun B continue or is that not possible until fun A returns from the
withContext
block?
e

ephemient

04/23/2021, 4:14 PM
regardless of the number of threads in the executor, coroutines may be interleaved at suspend points
🙏 1
who's calling A and B?
if A calls B then by design it'll wait until it's done before continuing
e

Erik

04/23/2021, 4:16 PM
Yes, in my case it turned out that A called B, but that's a particular situation
e

ephemient

04/23/2021, 4:16 PM
if it's some other code, and the dispatcher is full, then I believe that by default it'll fall back to Dispatchers.Default - so it may still run concurrently
e

Erik

04/23/2021, 4:17 PM
It looks like I'll have to do some more studying of the callers, order, mutable state, etc.
Thanks for the help, again
3 Views