Hi, are there any guarantees regarding the thread ...
# coroutines
t
Hi, are there any guarantees regarding the thread an
actor
is run within?
g
do you mean on which thread it runs?
t
yes - or at least that it doesnt change its thread between suspension points
g
there is no such guarantee, but you can set own custom dispatcher with a single thread What is your use case for it?
t
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
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
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
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
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 🤦‍♂️