Table of contents

Shared mutable state and concurrency

Coroutines can be executed concurrently using a multi-threaded dispatcher like the Dispatchers.Default. It presents all the usual concurrency problems. The main problem being synchronization of access to shared mutable state. Some solutions to this problem in the land of coroutines are similar to the solutions in the multi-threaded world, but others are unique.

The problem

Let us launch a hundred coroutines all doing the same action a thousand times. We’ll also measure their completion time for further comparisons:

  1. suspend fun massiveRun(action: suspend () -> Unit) {
  2. val n = 100 // number of coroutines to launch
  3. val k = 1000 // times an action is repeated by each coroutine
  4. val time = measureTimeMillis {
  5. coroutineScope { // scope for coroutines
  6. repeat(n) {
  7. launch {
  8. repeat(k) { action() }
  9. }
  10. }
  11. }
  12. }
  13. println("Completed ${n * k} actions in $time ms")
  14. }

We start with a very simple action that increments a shared mutable variable using multi-threaded Dispatchers.Default.

  1. import kotlinx.coroutines.*
  2. import kotlin.system.*
  3. suspend fun massiveRun(action: suspend () -> Unit) {
  4. val n = 100 // number of coroutines to launch
  5. val k = 1000 // times an action is repeated by each coroutine
  6. val time = measureTimeMillis {
  7. coroutineScope { // scope for coroutines
  8. repeat(n) {
  9. launch {
  10. repeat(k) { action() }
  11. }
  12. }
  13. }
  14. }
  15. println("Completed ${n * k} actions in $time ms")
  16. }
  17. //sampleStart
  18. var counter = 0
  19. fun main() = runBlocking {
  20. withContext(Dispatchers.Default) {
  21. massiveRun {
  22. counter++
  23. }
  24. }
  25. println("Counter = $counter")
  26. }
  27. //sampleEnd

You can get the full code here.

What does it print at the end? It is highly unlikely to ever print “Counter = 100000”, because a hundred coroutines increment the counter concurrently from multiple threads without any synchronization.

Volatiles are of no help

There is a common misconception that making a variable volatile solves concurrency problem. Let us try it:

  1. import kotlinx.coroutines.*
  2. import kotlin.system.*
  3. suspend fun massiveRun(action: suspend () -> Unit) {
  4. val n = 100 // number of coroutines to launch
  5. val k = 1000 // times an action is repeated by each coroutine
  6. val time = measureTimeMillis {
  7. coroutineScope { // scope for coroutines
  8. repeat(n) {
  9. launch {
  10. repeat(k) { action() }
  11. }
  12. }
  13. }
  14. }
  15. println("Completed ${n * k} actions in $time ms")
  16. }
  17. //sampleStart
  18. @Volatile // in Kotlin `volatile` is an annotation
  19. var counter = 0
  20. fun main() = runBlocking {
  21. withContext(Dispatchers.Default) {
  22. massiveRun {
  23. counter++
  24. }
  25. }
  26. println("Counter = $counter")
  27. }
  28. //sampleEnd

You can get the full code here.

This code works slower, but we still don’t get “Counter = 100000” at the end, because volatile variables guarantee linearizable (this is a technical term for “atomic”) reads and writes to the corresponding variable, but do not provide atomicity of larger actions (increment in our case).

Thread-safe data structures

The general solution that works both for threads and for coroutines is to use a thread-safe (aka synchronized, linearizable, or atomic) data structure that provides all the necessary synchronization for the corresponding operations that needs to be performed on a shared state. In the case of a simple counter we can use AtomicInteger class which has atomic incrementAndGet operations:

  1. import kotlinx.coroutines.*
  2. import java.util.concurrent.atomic.*
  3. import kotlin.system.*
  4. suspend fun massiveRun(action: suspend () -> Unit) {
  5. val n = 100 // number of coroutines to launch
  6. val k = 1000 // times an action is repeated by each coroutine
  7. val time = measureTimeMillis {
  8. coroutineScope { // scope for coroutines
  9. repeat(n) {
  10. launch {
  11. repeat(k) { action() }
  12. }
  13. }
  14. }
  15. }
  16. println("Completed ${n * k} actions in $time ms")
  17. }
  18. //sampleStart
  19. val counter = AtomicInteger()
  20. fun main() = runBlocking {
  21. withContext(Dispatchers.Default) {
  22. massiveRun {
  23. counter.incrementAndGet()
  24. }
  25. }
  26. println("Counter = $counter")
  27. }
  28. //sampleEnd

You can get the full code here.

This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other standard data structures and basic operations on them. However, it does not easily scale to complex state or to complex operations that do not have ready-to-use thread-safe implementations.

Thread confinement fine-grained

Thread confinement is an approach to the problem of shared mutable state where all access to the particular shared state is confined to a single thread. It is typically used in UI applications, where all UI state is confined to the single event-dispatch/application thread. It is easy to apply with coroutines by using a
single-threaded context.

  1. import kotlinx.coroutines.*
  2. import kotlin.system.*
  3. suspend fun massiveRun(action: suspend () -> Unit) {
  4. val n = 100 // number of coroutines to launch
  5. val k = 1000 // times an action is repeated by each coroutine
  6. val time = measureTimeMillis {
  7. coroutineScope { // scope for coroutines
  8. repeat(n) {
  9. launch {
  10. repeat(k) { action() }
  11. }
  12. }
  13. }
  14. }
  15. println("Completed ${n * k} actions in $time ms")
  16. }
  17. //sampleStart
  18. val counterContext = newSingleThreadContext("CounterContext")
  19. var counter = 0
  20. fun main() = runBlocking {
  21. withContext(Dispatchers.Default) {
  22. massiveRun {
  23. // confine each increment to a single-threaded context
  24. withContext(counterContext) {
  25. counter++
  26. }
  27. }
  28. }
  29. println("Counter = $counter")
  30. }
  31. //sampleEnd

You can get the full code here.

This code works very slowly, because it does fine-grained thread-confinement. Each individual increment switches from multi-threaded Dispatchers.Default context to the single-threaded context using withContext(counterContext) block.

Thread confinement coarse-grained

In practice, thread confinement is performed in large chunks, e.g. big pieces of state-updating business logic are confined to the single thread. The following example does it like that, running each coroutine in the single-threaded context to start with.

  1. import kotlinx.coroutines.*
  2. import kotlin.system.*
  3. suspend fun massiveRun(action: suspend () -> Unit) {
  4. val n = 100 // number of coroutines to launch
  5. val k = 1000 // times an action is repeated by each coroutine
  6. val time = measureTimeMillis {
  7. coroutineScope { // scope for coroutines
  8. repeat(n) {
  9. launch {
  10. repeat(k) { action() }
  11. }
  12. }
  13. }
  14. }
  15. println("Completed ${n * k} actions in $time ms")
  16. }
  17. //sampleStart
  18. val counterContext = newSingleThreadContext("CounterContext")
  19. var counter = 0
  20. fun main() = runBlocking {
  21. // confine everything to a single-threaded context
  22. withContext(counterContext) {
  23. massiveRun {
  24. counter++
  25. }
  26. }
  27. println("Counter = $counter")
  28. }
  29. //sampleEnd

You can get the full code here.

This now works much faster and produces correct result.

Mutual exclusion

Mutual exclusion solution to the problem is to protect all modifications of the shared state with a critical section that is never executed concurrently. In a blocking world you’d typically use synchronized or ReentrantLock for that. Coroutine’s alternative is called Mutex. It has lock and unlock functions to delimit a critical section. The key difference is that Mutex.lock() is a suspending function. It does not block a thread.

There is also withLock extension function that conveniently represents mutex.lock(); try { ... } finally { mutex.unlock() } pattern:

  1. import kotlinx.coroutines.*
  2. import kotlinx.coroutines.sync.*
  3. import kotlin.system.*
  4. suspend fun massiveRun(action: suspend () -> Unit) {
  5. val n = 100 // number of coroutines to launch
  6. val k = 1000 // times an action is repeated by each coroutine
  7. val time = measureTimeMillis {
  8. coroutineScope { // scope for coroutines
  9. repeat(n) {
  10. launch {
  11. repeat(k) { action() }
  12. }
  13. }
  14. }
  15. }
  16. println("Completed ${n * k} actions in $time ms")
  17. }
  18. //sampleStart
  19. val mutex = Mutex()
  20. var counter = 0
  21. fun main() = runBlocking {
  22. withContext(Dispatchers.Default) {
  23. massiveRun {
  24. // protect each increment with lock
  25. mutex.withLock {
  26. counter++
  27. }
  28. }
  29. }
  30. println("Counter = $counter")
  31. }
  32. //sampleEnd

You can get the full code here.

The locking in this example is fine-grained, so it pays the price. However, it is a good choice for some situations where you absolutely must modify some shared state periodically, but there is no natural thread that this state is confined to.

Actors

An actor is an entity made up of a combination of a coroutine, the state that is confined and encapsulated into this coroutine, and a channel to communicate with other coroutines. A simple actor can be written as a function, but an actor with a complex state is better suited for a class.

There is an actor coroutine builder that conveniently combines actor’s mailbox channel into its scope to receive messages from and combines the send channel into the resulting job object, so that a single reference to the actor can be carried around as its handle.

The first step of using an actor is to define a class of messages that an actor is going to process. Kotlin’s sealed classes are well suited for that purpose. We define CounterMsg sealed class with IncCounter message to increment a counter and GetCounter message to get its value. The later needs to send a response. A CompletableDeferred communication primitive, that represents a single value that will be known (communicated) in the future, is used here for that purpose.

  1. // Message types for counterActor
  2. sealed class CounterMsg
  3. object IncCounter : CounterMsg() // one-way message to increment counter
  4. class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // a request with reply

Then we define a function that launches an actor using an actor coroutine builder:

  1. // This function launches a new counter actor
  2. fun CoroutineScope.counterActor() = actor<CounterMsg> {
  3. var counter = 0 // actor state
  4. for (msg in channel) { // iterate over incoming messages
  5. when (msg) {
  6. is IncCounter -> counter++
  7. is GetCounter -> msg.response.complete(counter)
  8. }
  9. }
  10. }

The main code is straightforward:

  1. import kotlinx.coroutines.*
  2. import kotlinx.coroutines.channels.*
  3. import kotlin.system.*
  4. suspend fun massiveRun(action: suspend () -> Unit) {
  5. val n = 100 // number of coroutines to launch
  6. val k = 1000 // times an action is repeated by each coroutine
  7. val time = measureTimeMillis {
  8. coroutineScope { // scope for coroutines
  9. repeat(n) {
  10. launch {
  11. repeat(k) { action() }
  12. }
  13. }
  14. }
  15. }
  16. println("Completed ${n * k} actions in $time ms")
  17. }
  18. // Message types for counterActor
  19. sealed class CounterMsg
  20. object IncCounter : CounterMsg() // one-way message to increment counter
  21. class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // a request with reply
  22. // This function launches a new counter actor
  23. fun CoroutineScope.counterActor() = actor<CounterMsg> {
  24. var counter = 0 // actor state
  25. for (msg in channel) { // iterate over incoming messages
  26. when (msg) {
  27. is IncCounter -> counter++
  28. is GetCounter -> msg.response.complete(counter)
  29. }
  30. }
  31. }
  32. //sampleStart
  33. fun main() = runBlocking<Unit> {
  34. val counter = counterActor() // create the actor
  35. withContext(Dispatchers.Default) {
  36. massiveRun {
  37. counter.send(IncCounter)
  38. }
  39. }
  40. // send a message to get a counter value from an actor
  41. val response = CompletableDeferred<Int>()
  42. counter.send(GetCounter(response))
  43. println("Counter = ${response.await()}")
  44. counter.close() // shutdown the actor
  45. }
  46. //sampleEnd

You can get the full code here.

It does not matter (for correctness) what context the actor itself is executed in. An actor is a coroutine and a coroutine is executed sequentially, so confinement of the state to the specific coroutine works as a solution to the problem of shared mutable state. Indeed, actors may modify their own private state, but can only affect each other through messages (avoiding the need for any locks).

Actor is more efficient than locking under load, because in this case it always has work to do and it does not have to switch to a different context at all.

Note that an actor coroutine builder is a dual of produce coroutine builder. An actor is associated with the channel that it receives messages from, while a producer is associated with the channel that it sends elements to.