hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 1 | <!--- INCLUDE .*/example-([a-z]+)-([0-9a-z]+)\.kt |
| 2 | /* |
| 3 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
| 4 | */ |
| 5 | |
| 6 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
| 7 | package kotlinx.coroutines.experimental.guide.$$1$$2 |
| 8 | |
| 9 | import kotlinx.coroutines.experimental.* |
| 10 | --> |
| 11 | <!--- KNIT ../core/kotlinx-coroutines-core/test/guide/.*\.kt --> |
| 12 | <!--- TEST_OUT ../core/kotlinx-coroutines-core/test/guide/test/SharedStateGuideTest.kt |
| 13 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
| 14 | package kotlinx.coroutines.experimental.guide.test |
| 15 | |
| 16 | import org.junit.Test |
| 17 | |
| 18 | class SharedStateGuideTest { |
| 19 | --> |
| 20 | ## Table of contents |
| 21 | |
| 22 | <!--- TOC --> |
| 23 | |
| 24 | * [Shared mutable state and concurrency](#shared-mutable-state-and-concurrency) |
| 25 | * [The problem](#the-problem) |
| 26 | * [Volatiles are of no help](#volatiles-are-of-no-help) |
| 27 | * [Thread-safe data structures](#thread-safe-data-structures) |
| 28 | * [Thread confinement fine-grained](#thread-confinement-fine-grained) |
| 29 | * [Thread confinement coarse-grained](#thread-confinement-coarse-grained) |
| 30 | * [Mutual exclusion](#mutual-exclusion) |
| 31 | * [Actors](#actors) |
| 32 | |
| 33 | <!--- END_TOC --> |
| 34 | |
| 35 | ## Shared mutable state and concurrency |
| 36 | |
| 37 | Coroutines can be executed concurrently using a multi-threaded dispatcher like the [Dispatchers.Default]. It presents |
| 38 | all the usual concurrency problems. The main problem being synchronization of access to **shared mutable state**. |
| 39 | Some solutions to this problem in the land of coroutines are similar to the solutions in the multi-threaded world, |
| 40 | but others are unique. |
| 41 | |
| 42 | ### The problem |
| 43 | |
| 44 | Let us launch a hundred coroutines all doing the same action thousand times. |
| 45 | We'll also measure their completion time for further comparisons: |
| 46 | |
| 47 | <!--- INCLUDE .*/example-sync-03.kt |
| 48 | import java.util.concurrent.atomic.* |
| 49 | --> |
| 50 | |
| 51 | <!--- INCLUDE .*/example-sync-06.kt |
| 52 | import kotlinx.coroutines.experimental.sync.* |
| 53 | --> |
| 54 | |
| 55 | <!--- INCLUDE .*/example-sync-07.kt |
| 56 | import kotlinx.coroutines.experimental.channels.* |
| 57 | --> |
| 58 | |
| 59 | <!--- INCLUDE .*/example-sync-([0-9a-z]+).kt |
| 60 | import kotlin.system.* |
| 61 | import kotlin.coroutines.experimental.* |
| 62 | --> |
| 63 | |
| 64 | ```kotlin |
| 65 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 66 | val n = 100 // number of coroutines to launch |
| 67 | val k = 1000 // times an action is repeated by each coroutine |
| 68 | val time = measureTimeMillis { |
| 69 | val jobs = List(n) { |
| 70 | launch { |
| 71 | repeat(k) { action() } |
| 72 | } |
| 73 | } |
| 74 | jobs.forEach { it.join() } |
| 75 | } |
| 76 | println("Completed ${n * k} actions in $time ms") |
| 77 | } |
| 78 | ``` |
| 79 | |
| 80 | <!--- INCLUDE .*/example-sync-([0-9a-z]+).kt --> |
| 81 | |
| 82 | We start with a very simple action that increments a shared mutable variable using |
| 83 | multi-threaded [Dispatchers.Default] that is used in [GlobalScope]. |
| 84 | |
| 85 | ```kotlin |
| 86 | var counter = 0 |
| 87 | |
| 88 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 89 | GlobalScope.massiveRun { |
| 90 | counter++ |
| 91 | } |
| 92 | println("Counter = $counter") |
| 93 | } |
| 94 | ``` |
| 95 | |
| 96 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-01.kt) |
| 97 | |
| 98 | <!--- TEST LINES_START |
| 99 | Completed 100000 actions in |
| 100 | Counter = |
| 101 | --> |
| 102 | |
| 103 | What does it print at the end? It is highly unlikely to ever print "Counter = 100000", because a thousand coroutines |
| 104 | increment the `counter` concurrently from multiple threads without any synchronization. |
| 105 | |
| 106 | > Note: if you have an old system with 2 or fewer CPUs, then you _will_ consistently see 100000, because |
| 107 | the thread pool is running in only one thread in this case. To reproduce the problem you'll need to make the |
| 108 | following change: |
| 109 | |
| 110 | ```kotlin |
| 111 | val mtContext = newFixedThreadPoolContext(2, "mtPool") // explicitly define context with two threads |
| 112 | var counter = 0 |
| 113 | |
| 114 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 115 | CoroutineScope(mtContext).massiveRun { // use it instead of Dispatchers.Default in this sample and below |
| 116 | counter++ |
| 117 | } |
| 118 | println("Counter = $counter") |
| 119 | } |
| 120 | ``` |
| 121 | |
| 122 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-01b.kt) |
| 123 | |
| 124 | <!--- TEST LINES_START |
| 125 | Completed 100000 actions in |
| 126 | Counter = |
| 127 | --> |
| 128 | |
| 129 | ### Volatiles are of no help |
| 130 | |
| 131 | There is common misconception that making a variable `volatile` solves concurrency problem. Let us try it: |
| 132 | |
| 133 | ```kotlin |
| 134 | @Volatile // in Kotlin `volatile` is an annotation |
| 135 | var counter = 0 |
| 136 | |
| 137 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 138 | GlobalScope.massiveRun { |
| 139 | counter++ |
| 140 | } |
| 141 | println("Counter = $counter") |
| 142 | } |
| 143 | ``` |
| 144 | |
| 145 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-02.kt) |
| 146 | |
| 147 | <!--- TEST LINES_START |
| 148 | Completed 100000 actions in |
| 149 | Counter = |
| 150 | --> |
| 151 | |
| 152 | This code works slower, but we still don't get "Counter = 100000" at the end, because volatile variables guarantee |
| 153 | linearizable (this is a technical term for "atomic") reads and writes to the corresponding variable, but |
| 154 | do not provide atomicity of larger actions (increment in our case). |
| 155 | |
| 156 | ### Thread-safe data structures |
| 157 | |
| 158 | The general solution that works both for threads and for coroutines is to use a thread-safe (aka synchronized, |
| 159 | linearizable, or atomic) data structure that provides all the necessarily synchronization for the corresponding |
| 160 | operations that needs to be performed on a shared state. |
| 161 | In the case of a simple counter we can use `AtomicInteger` class which has atomic `incrementAndGet` operations: |
| 162 | |
| 163 | ```kotlin |
| 164 | var counter = AtomicInteger() |
| 165 | |
| 166 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 167 | GlobalScope.massiveRun { |
| 168 | counter.incrementAndGet() |
| 169 | } |
| 170 | println("Counter = ${counter.get()}") |
| 171 | } |
| 172 | ``` |
| 173 | |
| 174 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-03.kt) |
| 175 | |
| 176 | <!--- TEST ARBITRARY_TIME |
| 177 | Completed 100000 actions in xxx ms |
| 178 | Counter = 100000 |
| 179 | --> |
| 180 | |
| 181 | This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other |
| 182 | standard data structures and basic operations on them. However, it does not easily scale to complex |
| 183 | state or to complex operations that do not have ready-to-use thread-safe implementations. |
| 184 | |
| 185 | ### Thread confinement fine-grained |
| 186 | |
| 187 | _Thread confinement_ is an approach to the problem of shared mutable state where all access to the particular shared |
| 188 | state is confined to a single thread. It is typically used in UI applications, where all UI state is confined to |
| 189 | the single event-dispatch/application thread. It is easy to apply with coroutines by using a |
| 190 | single-threaded context. |
| 191 | |
| 192 | ```kotlin |
| 193 | val counterContext = newSingleThreadContext("CounterContext") |
| 194 | var counter = 0 |
| 195 | |
| 196 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 197 | GlobalScope.massiveRun { // run each coroutine with DefaultDispathcer |
| 198 | withContext(counterContext) { // but confine each increment to the single-threaded context |
| 199 | counter++ |
| 200 | } |
| 201 | } |
| 202 | println("Counter = $counter") |
| 203 | } |
| 204 | ``` |
| 205 | |
| 206 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-04.kt) |
| 207 | |
| 208 | <!--- TEST ARBITRARY_TIME |
| 209 | Completed 100000 actions in xxx ms |
| 210 | Counter = 100000 |
| 211 | --> |
| 212 | |
| 213 | This code works very slowly, because it does _fine-grained_ thread-confinement. Each individual increment switches |
| 214 | from multi-threaded [Dispatchers.Default] context to the single-threaded context using [withContext] block. |
| 215 | |
| 216 | ### Thread confinement coarse-grained |
| 217 | |
| 218 | In practice, thread confinement is performed in large chunks, e.g. big pieces of state-updating business logic |
| 219 | are confined to the single thread. The following example does it like that, running each coroutine in |
| 220 | the single-threaded context to start with. |
| 221 | Here we use [CoroutineScope()] function to convert coroutine context reference to [CoroutineScope]: |
| 222 | |
| 223 | ```kotlin |
| 224 | val counterContext = newSingleThreadContext("CounterContext") |
| 225 | var counter = 0 |
| 226 | |
| 227 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 228 | CoroutineScope(counterContext).massiveRun { // run each coroutine in the single-threaded context |
| 229 | counter++ |
| 230 | } |
| 231 | println("Counter = $counter") |
| 232 | } |
| 233 | ``` |
| 234 | |
| 235 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-05.kt) |
| 236 | |
| 237 | <!--- TEST ARBITRARY_TIME |
| 238 | Completed 100000 actions in xxx ms |
| 239 | Counter = 100000 |
| 240 | --> |
| 241 | |
| 242 | This now works much faster and produces correct result. |
| 243 | |
| 244 | ### Mutual exclusion |
| 245 | |
| 246 | Mutual exclusion solution to the problem is to protect all modifications of the shared state with a _critical section_ |
| 247 | that is never executed concurrently. In a blocking world you'd typically use `synchronized` or `ReentrantLock` for that. |
| 248 | Coroutine's alternative is called [Mutex]. It has [lock][Mutex.lock] and [unlock][Mutex.unlock] functions to |
| 249 | delimit a critical section. The key difference is that `Mutex.lock()` is a suspending function. It does not block a thread. |
| 250 | |
| 251 | There is also [withLock] extension function that conveniently represents |
| 252 | `mutex.lock(); try { ... } finally { mutex.unlock() }` pattern: |
| 253 | |
| 254 | ```kotlin |
| 255 | val mutex = Mutex() |
| 256 | var counter = 0 |
| 257 | |
| 258 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 259 | GlobalScope.massiveRun { |
| 260 | mutex.withLock { |
| 261 | counter++ |
| 262 | } |
| 263 | } |
| 264 | println("Counter = $counter") |
| 265 | } |
| 266 | ``` |
| 267 | |
| 268 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-06.kt) |
| 269 | |
| 270 | <!--- TEST ARBITRARY_TIME |
| 271 | Completed 100000 actions in xxx ms |
| 272 | Counter = 100000 |
| 273 | --> |
| 274 | |
| 275 | The locking in this example is fine-grained, so it pays the price. However, it is a good choice for some situations |
| 276 | where you absolutely must modify some shared state periodically, but there is no natural thread that this state |
| 277 | is confined to. |
| 278 | |
| 279 | ### Actors |
| 280 | |
| 281 | An [actor](https://en.wikipedia.org/wiki/Actor_model) is an entity made up of a combination of a coroutine, the state that is confined and encapsulated into this coroutine, |
| 282 | and a channel to communicate with other coroutines. A simple actor can be written as a function, |
| 283 | but an actor with a complex state is better suited for a class. |
| 284 | |
| 285 | There is an [actor] coroutine builder that conveniently combines actor's mailbox channel into its |
| 286 | scope to receive messages from and combines the send channel into the resulting job object, so that a |
| 287 | single reference to the actor can be carried around as its handle. |
| 288 | |
| 289 | The first step of using an actor is to define a class of messages that an actor is going to process. |
| 290 | Kotlin's [sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) are well suited for that purpose. |
| 291 | We define `CounterMsg` sealed class with `IncCounter` message to increment a counter and `GetCounter` message |
| 292 | to get its value. The later needs to send a response. A [CompletableDeferred] communication |
| 293 | primitive, that represents a single value that will be known (communicated) in the future, |
| 294 | is used here for that purpose. |
| 295 | |
| 296 | ```kotlin |
| 297 | // Message types for counterActor |
| 298 | sealed class CounterMsg |
| 299 | object IncCounter : CounterMsg() // one-way message to increment counter |
| 300 | class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // a request with reply |
| 301 | ``` |
| 302 | |
| 303 | Then we define a function that launches an actor using an [actor] coroutine builder: |
| 304 | |
| 305 | ```kotlin |
| 306 | // This function launches a new counter actor |
| 307 | fun CoroutineScope.counterActor() = actor<CounterMsg> { |
| 308 | var counter = 0 // actor state |
| 309 | for (msg in channel) { // iterate over incoming messages |
| 310 | when (msg) { |
| 311 | is IncCounter -> counter++ |
| 312 | is GetCounter -> msg.response.complete(counter) |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | ``` |
| 317 | |
| 318 | The main code is straightforward: |
| 319 | |
| 320 | ```kotlin |
| 321 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 322 | val counter = counterActor() // create the actor |
| 323 | GlobalScope.massiveRun { |
| 324 | counter.send(IncCounter) |
| 325 | } |
| 326 | // send a message to get a counter value from an actor |
| 327 | val response = CompletableDeferred<Int>() |
| 328 | counter.send(GetCounter(response)) |
| 329 | println("Counter = ${response.await()}") |
| 330 | counter.close() // shutdown the actor |
| 331 | } |
| 332 | ``` |
| 333 | |
| 334 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-07.kt) |
| 335 | |
| 336 | <!--- TEST ARBITRARY_TIME |
| 337 | Completed 100000 actions in xxx ms |
| 338 | Counter = 100000 |
| 339 | --> |
| 340 | |
| 341 | It does not matter (for correctness) what context the actor itself is executed in. An actor is |
| 342 | a coroutine and a coroutine is executed sequentially, so confinement of the state to the specific coroutine |
| 343 | 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). |
| 344 | |
| 345 | Actor is more efficient than locking under load, because in this case it always has work to do and it does not |
| 346 | have to switch to a different context at all. |
| 347 | |
| 348 | > Note, that an [actor] coroutine builder is a dual of [produce] coroutine builder. An actor is associated |
| 349 | with the channel that it receives messages from, while a producer is associated with the channel that it |
| 350 | sends elements to. |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame^] | 351 | |
| 352 | <!--- MODULE kotlinx-coroutines-core --> |
| 353 | <!--- INDEX kotlinx.coroutines.experimental --> |
| 354 | [Dispatchers.Default]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-dispatchers/-default.html |
| 355 | [GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-global-scope/index.html |
| 356 | [withContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-context.html |
| 357 | [CoroutineScope()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope.html |
| 358 | [CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/index.html |
| 359 | [CompletableDeferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-completable-deferred/index.html |
| 360 | <!--- INDEX kotlinx.coroutines.experimental.sync --> |
| 361 | [Mutex]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/index.html |
| 362 | [Mutex.lock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/lock.html |
| 363 | [Mutex.unlock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/unlock.html |
| 364 | [withLock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/with-lock.html |
| 365 | <!--- INDEX kotlinx.coroutines.experimental.channels --> |
| 366 | [actor]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/actor.html |
| 367 | [produce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/produce.html |
| 368 | <!--- END --> |