Coroutine Actors and thread-safety

The counter inside actor is safe because execution execution inside a coroutine is sequential in the precise, concurrency-theoretic definition of this term, i.e. all the operations in the coroutine are totally ordered with “happens before” relation (a book on concurrency theory like “The Art of Mutliprocessor Programming” is a highly recommended reading to understand it better).

So, there is no concurrency in a coroutine. How is that achieved? There are two cases. Execution in between suspension points follows normal JMM rules that state that operations on a single thread establish happens-before relation. Execution around suspension points has happens-before relation, because it is established by the synchronisation primitives that are used by implementations of suspending functions.

With respect to where the counter is defined. As long as you have only one instance of counterActor running, it does not matter whether counter variable is define inside the actor or outside of it. However, moving it outside of the code of counterActor is a bad idea for the same reason as global variables are a bad idea. If you start two instances of counterActor, then they will conflict on the global counter variable.

3 Likes