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

thana

10/12/2020, 6:15 AM
Hi, are there any guarantees regarding the thread an
actor
is run within?
g

gildor

10/12/2020, 6:29 AM
do you mean on which thread it runs?
t

thana

10/12/2020, 6:32 AM
yes - or at least that it doesnt change its thread between suspension points
g

gildor

10/12/2020, 6:33 AM
there is no such guarantee, but you can set own custom dispatcher with a single thread What is your use case for it?
t

thana

10/12/2020, 6:38 AM
i was thinking about how to use
actor
for stateful actors. one selling point of actors is, that you do not have to care about synchronization because its run within a single thread. now, if you spread execution between multiple threads you do have so synchonize access on mutable data. i think thats kinda ugly. You are right, it's possible to execute it with a single threaded execution context. but i wonder why there are no warning signs about that fact...
g

gildor

10/12/2020, 6:43 AM
do have so synchonize access on mutable data
No, if actor itself holds this data, or only if it only who modifies it, you don;’t need any syncronization in this case
actor suspend points can be dispatched on different threads, but actor code is completely sequential, so it doesn’t require syncronization, it’s the same what you have with any other suspend function
t

thana

10/12/2020, 6:49 AM
how does it not need synchronizsation between threads? the runtime is the jvm so we have to cope with java's memory model visibility guarantees, so if thread A modifies some variable there a certain guarantees about how and when thread B might see that changes value. So if i set a value, then suspend and then read the value, i have to synchronize my access to make sure i read the altest value
g

gildor

10/12/2020, 8:50 AM
java’s memory model visibility guarantees
Yes, but in suspend function you have all guarantees (every next line of suspend function invoked after of previous line with happens before guarantees, even if this call was also suspend)
So if i set a value, then suspend and then read the value
It doesn’t require any additional check
For more detailed explanation you can check this blog post from Roman (designer of kotlin coroutines) https://proandroiddev.com/what-is-concurrent-access-to-mutable-state-f386e5cb8292
t

thana

10/12/2020, 9:05 AM
ahh i wasn't aware of that, thanks 🙂
now that i'm think about, i should have really seen that point - of course we must guarantee the happens-before-ordering in coroutines, too 🤦‍♂️
3 Views