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