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