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. |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 7 | package kotlinx.coroutines.guide.$$1$$2 |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 8 | --> |
| 9 | <!--- KNIT ../core/kotlinx-coroutines-core/test/guide/.*\.kt --> |
| 10 | <!--- TEST_OUT ../core/kotlinx-coroutines-core/test/guide/test/SharedStateGuideTest.kt |
| 11 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 12 | package kotlinx.coroutines.guide.test |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 13 | |
| 14 | import org.junit.Test |
| 15 | |
| 16 | class SharedStateGuideTest { |
| 17 | --> |
| 18 | ## Table of contents |
| 19 | |
| 20 | <!--- TOC --> |
| 21 | |
| 22 | * [Shared mutable state and concurrency](#shared-mutable-state-and-concurrency) |
| 23 | * [The problem](#the-problem) |
| 24 | * [Volatiles are of no help](#volatiles-are-of-no-help) |
| 25 | * [Thread-safe data structures](#thread-safe-data-structures) |
| 26 | * [Thread confinement fine-grained](#thread-confinement-fine-grained) |
| 27 | * [Thread confinement coarse-grained](#thread-confinement-coarse-grained) |
| 28 | * [Mutual exclusion](#mutual-exclusion) |
| 29 | * [Actors](#actors) |
| 30 | |
| 31 | <!--- END_TOC --> |
| 32 | |
| 33 | ## Shared mutable state and concurrency |
| 34 | |
| 35 | Coroutines can be executed concurrently using a multi-threaded dispatcher like the [Dispatchers.Default]. It presents |
| 36 | all the usual concurrency problems. The main problem being synchronization of access to **shared mutable state**. |
| 37 | Some solutions to this problem in the land of coroutines are similar to the solutions in the multi-threaded world, |
| 38 | but others are unique. |
| 39 | |
| 40 | ### The problem |
| 41 | |
| 42 | Let us launch a hundred coroutines all doing the same action thousand times. |
| 43 | We'll also measure their completion time for further comparisons: |
| 44 | |
Robert GolusiĆski | c33ef61 | 2018-10-23 11:29:56 +0200 | [diff] [blame] | 45 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 46 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 47 | ```kotlin |
| 48 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 49 | val n = 100 // number of coroutines to launch |
| 50 | val k = 1000 // times an action is repeated by each coroutine |
| 51 | val time = measureTimeMillis { |
| 52 | val jobs = List(n) { |
| 53 | launch { |
| 54 | repeat(k) { action() } |
| 55 | } |
| 56 | } |
| 57 | jobs.forEach { it.join() } |
| 58 | } |
| 59 | println("Completed ${n * k} actions in $time ms") |
| 60 | } |
| 61 | ``` |
| 62 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 63 | </div> |
| 64 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 65 | We start with a very simple action that increments a shared mutable variable using |
| 66 | multi-threaded [Dispatchers.Default] that is used in [GlobalScope]. |
| 67 | |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 68 | <!--- CLEAR --> |
| 69 | |
| 70 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 71 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 72 | ```kotlin |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 73 | import kotlinx.coroutines.* |
| 74 | import kotlin.system.* |
| 75 | |
| 76 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 77 | val n = 100 // number of coroutines to launch |
| 78 | val k = 1000 // times an action is repeated by each coroutine |
| 79 | val time = measureTimeMillis { |
| 80 | val jobs = List(n) { |
| 81 | launch { |
| 82 | repeat(k) { action() } |
| 83 | } |
| 84 | } |
| 85 | jobs.forEach { it.join() } |
| 86 | } |
| 87 | println("Completed ${n * k} actions in $time ms") |
| 88 | } |
| 89 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 90 | var counter = 0 |
| 91 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 92 | fun main() = runBlocking<Unit> { |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 93 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 94 | GlobalScope.massiveRun { |
| 95 | counter++ |
| 96 | } |
| 97 | println("Counter = $counter") |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 98 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 99 | } |
| 100 | ``` |
| 101 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 102 | </div> |
| 103 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 104 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-01.kt) |
| 105 | |
| 106 | <!--- TEST LINES_START |
| 107 | Completed 100000 actions in |
| 108 | Counter = |
| 109 | --> |
| 110 | |
| 111 | What does it print at the end? It is highly unlikely to ever print "Counter = 100000", because a thousand coroutines |
| 112 | increment the `counter` concurrently from multiple threads without any synchronization. |
| 113 | |
| 114 | > Note: if you have an old system with 2 or fewer CPUs, then you _will_ consistently see 100000, because |
| 115 | the thread pool is running in only one thread in this case. To reproduce the problem you'll need to make the |
| 116 | following change: |
| 117 | |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 118 | <!--- CLEAR --> |
| 119 | |
| 120 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 121 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 122 | ```kotlin |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 123 | import kotlinx.coroutines.* |
| 124 | import kotlin.system.* |
| 125 | |
| 126 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 127 | val n = 100 // number of coroutines to launch |
| 128 | val k = 1000 // times an action is repeated by each coroutine |
| 129 | val time = measureTimeMillis { |
| 130 | val jobs = List(n) { |
| 131 | launch { |
| 132 | repeat(k) { action() } |
| 133 | } |
| 134 | } |
| 135 | jobs.forEach { it.join() } |
| 136 | } |
| 137 | println("Completed ${n * k} actions in $time ms") |
| 138 | } |
| 139 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 140 | val mtContext = newFixedThreadPoolContext(2, "mtPool") // explicitly define context with two threads |
| 141 | var counter = 0 |
| 142 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 143 | fun main() = runBlocking<Unit> { |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 144 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 145 | CoroutineScope(mtContext).massiveRun { // use it instead of Dispatchers.Default in this sample and below |
| 146 | counter++ |
| 147 | } |
| 148 | println("Counter = $counter") |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 149 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 150 | } |
| 151 | ``` |
| 152 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 153 | </div> |
| 154 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 155 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-01b.kt) |
| 156 | |
| 157 | <!--- TEST LINES_START |
| 158 | Completed 100000 actions in |
| 159 | Counter = |
| 160 | --> |
| 161 | |
| 162 | ### Volatiles are of no help |
| 163 | |
| 164 | There is common misconception that making a variable `volatile` solves concurrency problem. Let us try it: |
| 165 | |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 166 | <!--- CLEAR --> |
| 167 | |
| 168 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 169 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 170 | ```kotlin |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 171 | import kotlinx.coroutines.* |
| 172 | import kotlin.system.* |
| 173 | |
| 174 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 175 | val n = 100 // number of coroutines to launch |
| 176 | val k = 1000 // times an action is repeated by each coroutine |
| 177 | val time = measureTimeMillis { |
| 178 | val jobs = List(n) { |
| 179 | launch { |
| 180 | repeat(k) { action() } |
| 181 | } |
| 182 | } |
| 183 | jobs.forEach { it.join() } |
| 184 | } |
| 185 | println("Completed ${n * k} actions in $time ms") |
| 186 | } |
| 187 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 188 | @Volatile // in Kotlin `volatile` is an annotation |
| 189 | var counter = 0 |
| 190 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 191 | fun main() = runBlocking<Unit> { |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 192 | GlobalScope.massiveRun { |
| 193 | counter++ |
| 194 | } |
| 195 | println("Counter = $counter") |
| 196 | } |
| 197 | ``` |
| 198 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 199 | </div> |
| 200 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 201 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-02.kt) |
| 202 | |
| 203 | <!--- TEST LINES_START |
| 204 | Completed 100000 actions in |
| 205 | Counter = |
| 206 | --> |
| 207 | |
| 208 | This code works slower, but we still don't get "Counter = 100000" at the end, because volatile variables guarantee |
| 209 | linearizable (this is a technical term for "atomic") reads and writes to the corresponding variable, but |
| 210 | do not provide atomicity of larger actions (increment in our case). |
| 211 | |
| 212 | ### Thread-safe data structures |
| 213 | |
| 214 | The general solution that works both for threads and for coroutines is to use a thread-safe (aka synchronized, |
| 215 | linearizable, or atomic) data structure that provides all the necessarily synchronization for the corresponding |
| 216 | operations that needs to be performed on a shared state. |
| 217 | In the case of a simple counter we can use `AtomicInteger` class which has atomic `incrementAndGet` operations: |
| 218 | |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 219 | <!--- CLEAR --> |
| 220 | |
| 221 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 222 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 223 | ```kotlin |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 224 | import kotlinx.coroutines.* |
| 225 | import java.util.concurrent.atomic.* |
| 226 | import kotlin.system.* |
| 227 | |
| 228 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 229 | val n = 100 // number of coroutines to launch |
| 230 | val k = 1000 // times an action is repeated by each coroutine |
| 231 | val time = measureTimeMillis { |
| 232 | val jobs = List(n) { |
| 233 | launch { |
| 234 | repeat(k) { action() } |
| 235 | } |
| 236 | } |
| 237 | jobs.forEach { it.join() } |
| 238 | } |
| 239 | println("Completed ${n * k} actions in $time ms") |
| 240 | } |
| 241 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 242 | var counter = AtomicInteger() |
| 243 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 244 | fun main() = runBlocking<Unit> { |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 245 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 246 | GlobalScope.massiveRun { |
| 247 | counter.incrementAndGet() |
| 248 | } |
| 249 | println("Counter = ${counter.get()}") |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 250 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 251 | } |
| 252 | ``` |
| 253 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 254 | </div> |
| 255 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 256 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-03.kt) |
| 257 | |
| 258 | <!--- TEST ARBITRARY_TIME |
| 259 | Completed 100000 actions in xxx ms |
| 260 | Counter = 100000 |
| 261 | --> |
| 262 | |
| 263 | This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other |
| 264 | standard data structures and basic operations on them. However, it does not easily scale to complex |
| 265 | state or to complex operations that do not have ready-to-use thread-safe implementations. |
| 266 | |
| 267 | ### Thread confinement fine-grained |
| 268 | |
| 269 | _Thread confinement_ is an approach to the problem of shared mutable state where all access to the particular shared |
| 270 | state is confined to a single thread. It is typically used in UI applications, where all UI state is confined to |
| 271 | the single event-dispatch/application thread. It is easy to apply with coroutines by using a |
| 272 | single-threaded context. |
| 273 | |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 274 | <!--- CLEAR --> |
| 275 | |
| 276 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 277 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 278 | ```kotlin |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 279 | import kotlinx.coroutines.* |
| 280 | import kotlin.system.* |
| 281 | |
| 282 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 283 | val n = 100 // number of coroutines to launch |
| 284 | val k = 1000 // times an action is repeated by each coroutine |
| 285 | val time = measureTimeMillis { |
| 286 | val jobs = List(n) { |
| 287 | launch { |
| 288 | repeat(k) { action() } |
| 289 | } |
| 290 | } |
| 291 | jobs.forEach { it.join() } |
| 292 | } |
| 293 | println("Completed ${n * k} actions in $time ms") |
| 294 | } |
| 295 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 296 | val counterContext = newSingleThreadContext("CounterContext") |
| 297 | var counter = 0 |
| 298 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 299 | fun main() = runBlocking<Unit> { |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 300 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 301 | GlobalScope.massiveRun { // run each coroutine with DefaultDispathcer |
| 302 | withContext(counterContext) { // but confine each increment to the single-threaded context |
| 303 | counter++ |
| 304 | } |
| 305 | } |
| 306 | println("Counter = $counter") |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 307 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 308 | } |
| 309 | ``` |
| 310 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 311 | </div> |
| 312 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 313 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-04.kt) |
| 314 | |
| 315 | <!--- TEST ARBITRARY_TIME |
| 316 | Completed 100000 actions in xxx ms |
| 317 | Counter = 100000 |
| 318 | --> |
| 319 | |
| 320 | This code works very slowly, because it does _fine-grained_ thread-confinement. Each individual increment switches |
| 321 | from multi-threaded [Dispatchers.Default] context to the single-threaded context using [withContext] block. |
| 322 | |
| 323 | ### Thread confinement coarse-grained |
| 324 | |
| 325 | In practice, thread confinement is performed in large chunks, e.g. big pieces of state-updating business logic |
| 326 | are confined to the single thread. The following example does it like that, running each coroutine in |
| 327 | the single-threaded context to start with. |
| 328 | Here we use [CoroutineScope()] function to convert coroutine context reference to [CoroutineScope]: |
| 329 | |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 330 | <!--- CLEAR --> |
| 331 | |
| 332 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 333 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 334 | ```kotlin |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 335 | import kotlinx.coroutines.* |
| 336 | import kotlin.system.* |
| 337 | |
| 338 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 339 | val n = 100 // number of coroutines to launch |
| 340 | val k = 1000 // times an action is repeated by each coroutine |
| 341 | val time = measureTimeMillis { |
| 342 | val jobs = List(n) { |
| 343 | launch { |
| 344 | repeat(k) { action() } |
| 345 | } |
| 346 | } |
| 347 | jobs.forEach { it.join() } |
| 348 | } |
| 349 | println("Completed ${n * k} actions in $time ms") |
| 350 | } |
| 351 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 352 | val counterContext = newSingleThreadContext("CounterContext") |
| 353 | var counter = 0 |
| 354 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 355 | fun main() = runBlocking<Unit> { |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 356 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 357 | CoroutineScope(counterContext).massiveRun { // run each coroutine in the single-threaded context |
| 358 | counter++ |
| 359 | } |
| 360 | println("Counter = $counter") |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 361 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 362 | } |
| 363 | ``` |
| 364 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 365 | </div> |
| 366 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 367 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-05.kt) |
| 368 | |
| 369 | <!--- TEST ARBITRARY_TIME |
| 370 | Completed 100000 actions in xxx ms |
| 371 | Counter = 100000 |
| 372 | --> |
| 373 | |
| 374 | This now works much faster and produces correct result. |
| 375 | |
| 376 | ### Mutual exclusion |
| 377 | |
| 378 | Mutual exclusion solution to the problem is to protect all modifications of the shared state with a _critical section_ |
| 379 | that is never executed concurrently. In a blocking world you'd typically use `synchronized` or `ReentrantLock` for that. |
| 380 | Coroutine's alternative is called [Mutex]. It has [lock][Mutex.lock] and [unlock][Mutex.unlock] functions to |
| 381 | delimit a critical section. The key difference is that `Mutex.lock()` is a suspending function. It does not block a thread. |
| 382 | |
| 383 | There is also [withLock] extension function that conveniently represents |
| 384 | `mutex.lock(); try { ... } finally { mutex.unlock() }` pattern: |
| 385 | |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 386 | <!--- CLEAR --> |
| 387 | |
| 388 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 389 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 390 | ```kotlin |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 391 | import kotlinx.coroutines.* |
| 392 | import kotlinx.coroutines.sync.* |
| 393 | import kotlin.system.* |
| 394 | |
| 395 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 396 | val n = 100 // number of coroutines to launch |
| 397 | val k = 1000 // times an action is repeated by each coroutine |
| 398 | val time = measureTimeMillis { |
| 399 | val jobs = List(n) { |
| 400 | launch { |
| 401 | repeat(k) { action() } |
| 402 | } |
| 403 | } |
| 404 | jobs.forEach { it.join() } |
| 405 | } |
| 406 | println("Completed ${n * k} actions in $time ms") |
| 407 | } |
| 408 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 409 | val mutex = Mutex() |
| 410 | var counter = 0 |
| 411 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 412 | fun main() = runBlocking<Unit> { |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 413 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 414 | GlobalScope.massiveRun { |
| 415 | mutex.withLock { |
| 416 | counter++ |
| 417 | } |
| 418 | } |
| 419 | println("Counter = $counter") |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 420 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 421 | } |
| 422 | ``` |
| 423 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 424 | </div> |
| 425 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 426 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-06.kt) |
| 427 | |
| 428 | <!--- TEST ARBITRARY_TIME |
| 429 | Completed 100000 actions in xxx ms |
| 430 | Counter = 100000 |
| 431 | --> |
| 432 | |
| 433 | The locking in this example is fine-grained, so it pays the price. However, it is a good choice for some situations |
| 434 | where you absolutely must modify some shared state periodically, but there is no natural thread that this state |
| 435 | is confined to. |
| 436 | |
| 437 | ### Actors |
| 438 | |
| 439 | 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, |
| 440 | and a channel to communicate with other coroutines. A simple actor can be written as a function, |
| 441 | but an actor with a complex state is better suited for a class. |
| 442 | |
| 443 | There is an [actor] coroutine builder that conveniently combines actor's mailbox channel into its |
| 444 | scope to receive messages from and combines the send channel into the resulting job object, so that a |
| 445 | single reference to the actor can be carried around as its handle. |
| 446 | |
| 447 | The first step of using an actor is to define a class of messages that an actor is going to process. |
| 448 | Kotlin's [sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) are well suited for that purpose. |
| 449 | We define `CounterMsg` sealed class with `IncCounter` message to increment a counter and `GetCounter` message |
| 450 | to get its value. The later needs to send a response. A [CompletableDeferred] communication |
| 451 | primitive, that represents a single value that will be known (communicated) in the future, |
| 452 | is used here for that purpose. |
| 453 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 454 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 455 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 456 | ```kotlin |
| 457 | // Message types for counterActor |
| 458 | sealed class CounterMsg |
| 459 | object IncCounter : CounterMsg() // one-way message to increment counter |
| 460 | class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // a request with reply |
| 461 | ``` |
| 462 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 463 | </div> |
| 464 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 465 | Then we define a function that launches an actor using an [actor] coroutine builder: |
| 466 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 467 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 468 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 469 | ```kotlin |
| 470 | // This function launches a new counter actor |
| 471 | fun CoroutineScope.counterActor() = actor<CounterMsg> { |
| 472 | var counter = 0 // actor state |
| 473 | for (msg in channel) { // iterate over incoming messages |
| 474 | when (msg) { |
| 475 | is IncCounter -> counter++ |
| 476 | is GetCounter -> msg.response.complete(counter) |
| 477 | } |
| 478 | } |
| 479 | } |
| 480 | ``` |
| 481 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 482 | </div> |
| 483 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 484 | The main code is straightforward: |
| 485 | |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 486 | <!--- CLEAR --> |
| 487 | |
| 488 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 489 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 490 | ```kotlin |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 491 | import kotlinx.coroutines.* |
| 492 | import kotlinx.coroutines.channels.* |
| 493 | import kotlin.system.* |
| 494 | |
| 495 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 496 | val n = 100 // number of coroutines to launch |
| 497 | val k = 1000 // times an action is repeated by each coroutine |
| 498 | val time = measureTimeMillis { |
| 499 | val jobs = List(n) { |
| 500 | launch { |
| 501 | repeat(k) { action() } |
| 502 | } |
| 503 | } |
| 504 | jobs.forEach { it.join() } |
| 505 | } |
| 506 | println("Completed ${n * k} actions in $time ms") |
| 507 | } |
| 508 | |
| 509 | // Message types for counterActor |
| 510 | sealed class CounterMsg |
| 511 | object IncCounter : CounterMsg() // one-way message to increment counter |
| 512 | class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // a request with reply |
| 513 | |
| 514 | // This function launches a new counter actor |
| 515 | fun CoroutineScope.counterActor() = actor<CounterMsg> { |
| 516 | var counter = 0 // actor state |
| 517 | for (msg in channel) { // iterate over incoming messages |
| 518 | when (msg) { |
| 519 | is IncCounter -> counter++ |
| 520 | is GetCounter -> msg.response.complete(counter) |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 525 | fun main() = runBlocking<Unit> { |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 526 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 527 | val counter = counterActor() // create the actor |
| 528 | GlobalScope.massiveRun { |
| 529 | counter.send(IncCounter) |
| 530 | } |
| 531 | // send a message to get a counter value from an actor |
| 532 | val response = CompletableDeferred<Int>() |
| 533 | counter.send(GetCounter(response)) |
| 534 | println("Counter = ${response.await()}") |
| 535 | counter.close() // shutdown the actor |
Prendota | 0eee3c3 | 2018-10-22 12:52:56 +0300 | [diff] [blame] | 536 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 537 | } |
| 538 | ``` |
| 539 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 540 | </div> |
| 541 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 542 | > You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-07.kt) |
| 543 | |
| 544 | <!--- TEST ARBITRARY_TIME |
| 545 | Completed 100000 actions in xxx ms |
| 546 | Counter = 100000 |
| 547 | --> |
| 548 | |
| 549 | It does not matter (for correctness) what context the actor itself is executed in. An actor is |
| 550 | a coroutine and a coroutine is executed sequentially, so confinement of the state to the specific coroutine |
| 551 | 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). |
| 552 | |
| 553 | Actor is more efficient than locking under load, because in this case it always has work to do and it does not |
| 554 | have to switch to a different context at all. |
| 555 | |
| 556 | > Note, that an [actor] coroutine builder is a dual of [produce] coroutine builder. An actor is associated |
| 557 | with the channel that it receives messages from, while a producer is associated with the channel that it |
| 558 | sends elements to. |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 559 | |
| 560 | <!--- MODULE kotlinx-coroutines-core --> |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 561 | <!--- INDEX kotlinx.coroutines --> |
| 562 | [Dispatchers.Default]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html |
| 563 | [GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html |
| 564 | [withContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html |
| 565 | [CoroutineScope()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope.html |
| 566 | [CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html |
| 567 | [CompletableDeferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-completable-deferred/index.html |
| 568 | <!--- INDEX kotlinx.coroutines.sync --> |
| 569 | [Mutex]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/index.html |
| 570 | [Mutex.lock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/lock.html |
| 571 | [Mutex.unlock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/unlock.html |
| 572 | [withLock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/with-lock.html |
| 573 | <!--- INDEX kotlinx.coroutines.channels --> |
| 574 | [actor]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/actor.html |
| 575 | [produce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/produce.html |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 576 | <!--- END --> |