Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1 | <!--- INCLUDE .*/example-([a-z]+)-([0-9]+)\.kt |
| 2 | /* |
| 3 | * Copyright 2016-2017 JetBrains s.r.o. |
| 4 | * |
| 5 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | * you may not use this file except in compliance with the License. |
| 7 | * You may obtain a copy of the License at |
| 8 | * |
| 9 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | * |
| 11 | * Unless required by applicable law or agreed to in writing, software |
| 12 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | * See the License for the specific language governing permissions and |
| 15 | * limitations under the License. |
| 16 | */ |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 17 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 18 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
| 19 | package guide.$$1.example$$2 |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 20 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 21 | import kotlinx.coroutines.experimental.* |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 22 | --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 23 | <!--- KNIT kotlinx-coroutines-core/src/test/kotlin/guide/.*\.kt --> |
| 24 | <!--- TEST_OUT kotlinx-coroutines-core/src/test/kotlin/guide/test/GuideTest.kt |
| 25 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
| 26 | package guide.test |
| 27 | |
| 28 | import org.junit.Test |
| 29 | |
| 30 | class GuideTest { |
| 31 | --> |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 32 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 33 | # Guide to kotlinx.coroutines by example |
| 34 | |
| 35 | This is a short guide on core features of `kotlinx.coroutines` with a series of examples. |
| 36 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 37 | ## Table of contents |
| 38 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 39 | <!--- TOC --> |
| 40 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 41 | * [Coroutine basics](#coroutine-basics) |
| 42 | * [Your first coroutine](#your-first-coroutine) |
| 43 | * [Bridging blocking and non-blocking worlds](#bridging-blocking-and-non-blocking-worlds) |
| 44 | * [Waiting for a job](#waiting-for-a-job) |
| 45 | * [Extract function refactoring](#extract-function-refactoring) |
| 46 | * [Coroutines ARE light-weight](#coroutines-are-light-weight) |
| 47 | * [Coroutines are like daemon threads](#coroutines-are-like-daemon-threads) |
| 48 | * [Cancellation and timeouts](#cancellation-and-timeouts) |
| 49 | * [Cancelling coroutine execution](#cancelling-coroutine-execution) |
| 50 | * [Cancellation is cooperative](#cancellation-is-cooperative) |
| 51 | * [Making computation code cancellable](#making-computation-code-cancellable) |
| 52 | * [Closing resources with finally](#closing-resources-with-finally) |
| 53 | * [Run non-cancellable block](#run-non-cancellable-block) |
| 54 | * [Timeout](#timeout) |
| 55 | * [Composing suspending functions](#composing-suspending-functions) |
| 56 | * [Sequential by default](#sequential-by-default) |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 57 | * [Concurrent using async](#concurrent-using-async) |
| 58 | * [Lazily started async](#lazily-started-async) |
| 59 | * [Async-style functions](#async-style-functions) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 60 | * [Coroutine context and dispatchers](#coroutine-context-and-dispatchers) |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 61 | * [Dispatchers and threads](#dispatchers-and-threads) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 62 | * [Unconfined vs confined dispatcher](#unconfined-vs-confined-dispatcher) |
| 63 | * [Debugging coroutines and threads](#debugging-coroutines-and-threads) |
| 64 | * [Jumping between threads](#jumping-between-threads) |
| 65 | * [Job in the context](#job-in-the-context) |
| 66 | * [Children of a coroutine](#children-of-a-coroutine) |
| 67 | * [Combining contexts](#combining-contexts) |
| 68 | * [Naming coroutines for debugging](#naming-coroutines-for-debugging) |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 69 | * [Cancellation via explicit job](#cancellation-via-explicit-job) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 70 | * [Channels](#channels) |
| 71 | * [Channel basics](#channel-basics) |
| 72 | * [Closing and iteration over channels](#closing-and-iteration-over-channels) |
| 73 | * [Building channel producers](#building-channel-producers) |
| 74 | * [Pipelines](#pipelines) |
| 75 | * [Prime numbers with pipeline](#prime-numbers-with-pipeline) |
| 76 | * [Fan-out](#fan-out) |
| 77 | * [Fan-in](#fan-in) |
| 78 | * [Buffered channels](#buffered-channels) |
Roman Elizarov | b0517ba | 2017-02-27 14:03:14 +0300 | [diff] [blame] | 79 | * [Channels are fair](#channels-are-fair) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 80 | * [Shared mutable state and concurrency](#shared-mutable-state-and-concurrency) |
| 81 | * [The problem](#the-problem) |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 82 | * [Volatiles are of no help](#volatiles-are-of-no-help) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 83 | * [Thread-safe data structures](#thread-safe-data-structures) |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 84 | * [Thread confinement fine-grained](#thread-confinement-fine-grained) |
| 85 | * [Thread confinement coarse-grained](#thread-confinement-coarse-grained) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 86 | * [Mutual exclusion](#mutual-exclusion) |
| 87 | * [Actors](#actors) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 88 | * [Select expression](#select-expression) |
| 89 | * [Selecting from channels](#selecting-from-channels) |
| 90 | * [Selecting on close](#selecting-on-close) |
| 91 | * [Selecting to send](#selecting-to-send) |
| 92 | * [Selecting deferred values](#selecting-deferred-values) |
| 93 | * [Switch over a channel of deferred values](#switch-over-a-channel-of-deferred-values) |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 94 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 95 | <!--- END_TOC --> |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 96 | |
| 97 | ## Coroutine basics |
| 98 | |
| 99 | This section covers basic coroutine concepts. |
| 100 | |
| 101 | ### Your first coroutine |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 102 | |
| 103 | Run the following code: |
| 104 | |
| 105 | ```kotlin |
| 106 | fun main(args: Array<String>) { |
| 107 | launch(CommonPool) { // create new coroutine in common thread pool |
| 108 | delay(1000L) // non-blocking delay for 1 second (default time unit is ms) |
| 109 | println("World!") // print after delay |
| 110 | } |
| 111 | println("Hello,") // main function continues while coroutine is delayed |
| 112 | Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive |
| 113 | } |
| 114 | ``` |
| 115 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 116 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-01.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 117 | |
| 118 | Run this code: |
| 119 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 120 | ```text |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 121 | Hello, |
| 122 | World! |
| 123 | ``` |
| 124 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 125 | <!--- TEST --> |
| 126 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 127 | Essentially, coroutines are light-weight threads. |
| 128 | They are launched with [launch] _coroutine builder_. |
| 129 | You can achieve the same result replacing |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 130 | `launch(CommonPool) { ... }` with `thread { ... }` and `delay(...)` with `Thread.sleep(...)`. Try it. |
| 131 | |
| 132 | If you start by replacing `launch(CommonPool)` by `thread`, the compiler produces the following error: |
| 133 | |
| 134 | ``` |
| 135 | Error: Kotlin: Suspend functions are only allowed to be called from a coroutine or another suspend function |
| 136 | ``` |
| 137 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 138 | That is because [delay] is a special _suspending function_ that does not block a thread, but _suspends_ |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 139 | coroutine and it can be only used from a coroutine. |
| 140 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 141 | ### Bridging blocking and non-blocking worlds |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 142 | |
| 143 | The first example mixes _non-blocking_ `delay(...)` and _blocking_ `Thread.sleep(...)` in the same |
| 144 | code of `main` function. It is easy to get lost. Let's cleanly separate blocking and non-blocking |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 145 | worlds by using [runBlocking]: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 146 | |
| 147 | ```kotlin |
| 148 | fun main(args: Array<String>) = runBlocking<Unit> { // start main coroutine |
| 149 | launch(CommonPool) { // create new coroutine in common thread pool |
| 150 | delay(1000L) |
| 151 | println("World!") |
| 152 | } |
| 153 | println("Hello,") // main coroutine continues while child is delayed |
| 154 | delay(2000L) // non-blocking delay for 2 seconds to keep JVM alive |
| 155 | } |
| 156 | ``` |
| 157 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 158 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-02.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 159 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 160 | <!--- TEST |
| 161 | Hello, |
| 162 | World! |
| 163 | --> |
| 164 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 165 | The result is the same, but this code uses only non-blocking [delay]. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 166 | |
| 167 | `runBlocking { ... }` works as an adaptor that is used here to start the top-level main coroutine. |
| 168 | The regular code outside of `runBlocking` _blocks_, until the coroutine inside `runBlocking` is active. |
| 169 | |
| 170 | This is also a way to write unit-tests for suspending functions: |
| 171 | |
| 172 | ```kotlin |
| 173 | class MyTest { |
| 174 | @Test |
| 175 | fun testMySuspendingFunction() = runBlocking<Unit> { |
| 176 | // here we can use suspending functions using any assertion style that we like |
| 177 | } |
| 178 | } |
| 179 | ``` |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 180 | |
| 181 | <!--- CLEAR --> |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 182 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 183 | ### Waiting for a job |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 184 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 185 | Delaying for a time while another coroutine is working is not a good approach. Let's explicitly |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 186 | wait (in a non-blocking way) until the background [Job] that we have launched is complete: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 187 | |
| 188 | ```kotlin |
| 189 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 190 | val job = launch(CommonPool) { // create new coroutine and keep a reference to its Job |
| 191 | delay(1000L) |
| 192 | println("World!") |
| 193 | } |
| 194 | println("Hello,") |
| 195 | job.join() // wait until child coroutine completes |
| 196 | } |
| 197 | ``` |
| 198 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 199 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-03.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 200 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 201 | <!--- TEST |
| 202 | Hello, |
| 203 | World! |
| 204 | --> |
| 205 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 206 | Now the result is still the same, but the code of the main coroutine is not tied to the duration of |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 207 | the background job in any way. Much better. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 208 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 209 | ### Extract function refactoring |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 210 | |
| 211 | Let's extract the block of code inside `launch(CommonPool} { ... }` into a separate function. When you |
| 212 | perform "Extract function" refactoring on this code you get a new function with `suspend` modifier. |
| 213 | That is your first _suspending function_. Suspending functions can be used inside coroutines |
| 214 | just like regular functions, but their additional feature is that they can, in turn, |
| 215 | use other suspending functions, like `delay` in this example, to _suspend_ execution of a coroutine. |
| 216 | |
| 217 | ```kotlin |
| 218 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 219 | val job = launch(CommonPool) { doWorld() } |
| 220 | println("Hello,") |
| 221 | job.join() |
| 222 | } |
| 223 | |
| 224 | // this is your first suspending function |
| 225 | suspend fun doWorld() { |
| 226 | delay(1000L) |
| 227 | println("World!") |
| 228 | } |
| 229 | ``` |
| 230 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 231 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-04.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 232 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 233 | <!--- TEST |
| 234 | Hello, |
| 235 | World! |
| 236 | --> |
| 237 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 238 | ### Coroutines ARE light-weight |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 239 | |
| 240 | Run the following code: |
| 241 | |
| 242 | ```kotlin |
| 243 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 244 | val jobs = List(100_000) { // create a lot of coroutines and list their jobs |
| 245 | launch(CommonPool) { |
| 246 | delay(1000L) |
| 247 | print(".") |
| 248 | } |
| 249 | } |
| 250 | jobs.forEach { it.join() } // wait for all jobs to complete |
| 251 | } |
| 252 | ``` |
| 253 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 254 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-05.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 255 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 256 | <!--- TEST lines.size == 1 && lines[0] == ".".repeat(100_000) --> |
| 257 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 258 | It starts 100K coroutines and, after a second, each coroutine prints a dot. |
| 259 | Now, try that with threads. What would happen? (Most likely your code will produce some sort of out-of-memory error) |
| 260 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 261 | ### Coroutines are like daemon threads |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 262 | |
| 263 | The following code launches a long-running coroutine that prints "I'm sleeping" twice a second and then |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 264 | returns from the main function after some delay: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 265 | |
| 266 | ```kotlin |
| 267 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 268 | launch(CommonPool) { |
| 269 | repeat(1000) { i -> |
| 270 | println("I'm sleeping $i ...") |
| 271 | delay(500L) |
| 272 | } |
| 273 | } |
| 274 | delay(1300L) // just quit after delay |
| 275 | } |
| 276 | ``` |
| 277 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 278 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-06.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 279 | |
| 280 | You can run and see that it prints three lines and terminates: |
| 281 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 282 | ```text |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 283 | I'm sleeping 0 ... |
| 284 | I'm sleeping 1 ... |
| 285 | I'm sleeping 2 ... |
| 286 | ``` |
| 287 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 288 | <!--- TEST --> |
| 289 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 290 | Active coroutines do not keep the process alive. They are like daemon threads. |
| 291 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 292 | ## Cancellation and timeouts |
| 293 | |
| 294 | This section covers coroutine cancellation and timeouts. |
| 295 | |
| 296 | ### Cancelling coroutine execution |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 297 | |
| 298 | In small application the return from "main" method might sound like a good idea to get all coroutines |
| 299 | implicitly terminated. In a larger, long-running application, you need finer-grained control. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 300 | The [launch] function returns a [Job] that can be used to cancel running coroutine: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 301 | |
| 302 | ```kotlin |
| 303 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 304 | val job = launch(CommonPool) { |
| 305 | repeat(1000) { i -> |
| 306 | println("I'm sleeping $i ...") |
| 307 | delay(500L) |
| 308 | } |
| 309 | } |
| 310 | delay(1300L) // delay a bit |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 311 | println("main: I'm tired of waiting!") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 312 | job.cancel() // cancels the job |
| 313 | delay(1300L) // delay a bit to ensure it was cancelled indeed |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 314 | println("main: Now I can quit.") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 315 | } |
| 316 | ``` |
| 317 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 318 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-01.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 319 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 320 | It produces the following output: |
| 321 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 322 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 323 | I'm sleeping 0 ... |
| 324 | I'm sleeping 1 ... |
| 325 | I'm sleeping 2 ... |
| 326 | main: I'm tired of waiting! |
| 327 | main: Now I can quit. |
| 328 | ``` |
| 329 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 330 | <!--- TEST --> |
| 331 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 332 | As soon as main invokes `job.cancel`, we don't see any output from the other coroutine because it was cancelled. |
| 333 | |
| 334 | ### Cancellation is cooperative |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 335 | |
Tair Rzayev | af73462 | 2017-02-01 22:30:16 +0200 | [diff] [blame] | 336 | Coroutine cancellation is _cooperative_. A coroutine code has to cooperate to be cancellable. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 337 | All the suspending functions in `kotlinx.coroutines` are _cancellable_. They check for cancellation of |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 338 | coroutine and throw [CancellationException] when cancelled. However, if a coroutine is working in |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 339 | a computation and does not check for cancellation, then it cannot be cancelled, like the following |
| 340 | example shows: |
| 341 | |
| 342 | ```kotlin |
| 343 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 344 | val job = launch(CommonPool) { |
| 345 | var nextPrintTime = 0L |
| 346 | var i = 0 |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 347 | while (i < 10) { // computation loop |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 348 | val currentTime = System.currentTimeMillis() |
| 349 | if (currentTime >= nextPrintTime) { |
| 350 | println("I'm sleeping ${i++} ...") |
| 351 | nextPrintTime = currentTime + 500L |
| 352 | } |
| 353 | } |
| 354 | } |
| 355 | delay(1300L) // delay a bit |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 356 | println("main: I'm tired of waiting!") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 357 | job.cancel() // cancels the job |
| 358 | delay(1300L) // delay a bit to see if it was cancelled.... |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 359 | println("main: Now I can quit.") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 360 | } |
| 361 | ``` |
| 362 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 363 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-02.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 364 | |
| 365 | Run it to see that it continues to print "I'm sleeping" even after cancellation. |
| 366 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 367 | <!--- TEST |
| 368 | I'm sleeping 0 ... |
| 369 | I'm sleeping 1 ... |
| 370 | I'm sleeping 2 ... |
| 371 | main: I'm tired of waiting! |
| 372 | I'm sleeping 3 ... |
| 373 | I'm sleeping 4 ... |
| 374 | I'm sleeping 5 ... |
| 375 | main: Now I can quit. |
| 376 | --> |
| 377 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 378 | ### Making computation code cancellable |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 379 | |
| 380 | There are two approaches to making computation code cancellable. The first one is to periodically |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 381 | invoke a suspending function. There is a [yield] function that is a good choice for that purpose. |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 382 | The other one is to explicitly check the cancellation status. Let us try the later approach. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 383 | |
| 384 | Replace `while (true)` in the previous example with `while (isActive)` and rerun it. |
| 385 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 386 | ```kotlin |
| 387 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 388 | val job = launch(CommonPool) { |
| 389 | var nextPrintTime = 0L |
| 390 | var i = 0 |
| 391 | while (isActive) { // cancellable computation loop |
| 392 | val currentTime = System.currentTimeMillis() |
| 393 | if (currentTime >= nextPrintTime) { |
| 394 | println("I'm sleeping ${i++} ...") |
| 395 | nextPrintTime = currentTime + 500L |
| 396 | } |
| 397 | } |
| 398 | } |
| 399 | delay(1300L) // delay a bit |
| 400 | println("main: I'm tired of waiting!") |
| 401 | job.cancel() // cancels the job |
| 402 | delay(1300L) // delay a bit to see if it was cancelled.... |
| 403 | println("main: Now I can quit.") |
| 404 | } |
| 405 | ``` |
| 406 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 407 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-03.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 408 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 409 | As you can see, now this loop can be cancelled. [isActive][CoroutineScope.isActive] is a property that is available inside |
| 410 | the code of coroutines via [CoroutineScope] object. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 411 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 412 | <!--- TEST |
| 413 | I'm sleeping 0 ... |
| 414 | I'm sleeping 1 ... |
| 415 | I'm sleeping 2 ... |
| 416 | main: I'm tired of waiting! |
| 417 | main: Now I can quit. |
| 418 | --> |
| 419 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 420 | ### Closing resources with finally |
| 421 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 422 | Cancellable suspending functions throw [CancellationException] on cancellation which can be handled in |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 423 | all the usual way. For example, the `try {...} finally {...}` and Kotlin `use` function execute their |
| 424 | finalization actions normally when coroutine is cancelled: |
| 425 | |
| 426 | ```kotlin |
| 427 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 428 | val job = launch(CommonPool) { |
| 429 | try { |
| 430 | repeat(1000) { i -> |
| 431 | println("I'm sleeping $i ...") |
| 432 | delay(500L) |
| 433 | } |
| 434 | } finally { |
| 435 | println("I'm running finally") |
| 436 | } |
| 437 | } |
| 438 | delay(1300L) // delay a bit |
| 439 | println("main: I'm tired of waiting!") |
| 440 | job.cancel() // cancels the job |
| 441 | delay(1300L) // delay a bit to ensure it was cancelled indeed |
| 442 | println("main: Now I can quit.") |
| 443 | } |
| 444 | ``` |
| 445 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 446 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-04.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 447 | |
| 448 | The example above produces the following output: |
| 449 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 450 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 451 | I'm sleeping 0 ... |
| 452 | I'm sleeping 1 ... |
| 453 | I'm sleeping 2 ... |
| 454 | main: I'm tired of waiting! |
| 455 | I'm running finally |
| 456 | main: Now I can quit. |
| 457 | ``` |
| 458 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 459 | <!--- TEST --> |
| 460 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 461 | ### Run non-cancellable block |
| 462 | |
| 463 | Any attempt to use a suspending function in the `finally` block of the previous example will cause |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 464 | [CancellationException], because the coroutine running this code is cancelled. Usually, this is not a |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 465 | problem, since all well-behaving closing operations (closing a file, cancelling a job, or closing any kind of a |
| 466 | communication channel) are usually non-blocking and do not involve any suspending functions. However, in the |
| 467 | rare case when you need to suspend in the cancelled coroutine you can wrap the corresponding code in |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 468 | `run(NonCancellable) {...}` using [run] function and [NonCancellable] context as the following example shows: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 469 | |
| 470 | ```kotlin |
| 471 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 472 | val job = launch(CommonPool) { |
| 473 | try { |
| 474 | repeat(1000) { i -> |
| 475 | println("I'm sleeping $i ...") |
| 476 | delay(500L) |
| 477 | } |
| 478 | } finally { |
| 479 | run(NonCancellable) { |
| 480 | println("I'm running finally") |
| 481 | delay(1000L) |
| 482 | println("And I've just delayed for 1 sec because I'm non-cancellable") |
| 483 | } |
| 484 | } |
| 485 | } |
| 486 | delay(1300L) // delay a bit |
| 487 | println("main: I'm tired of waiting!") |
| 488 | job.cancel() // cancels the job |
| 489 | delay(1300L) // delay a bit to ensure it was cancelled indeed |
| 490 | println("main: Now I can quit.") |
| 491 | } |
| 492 | ``` |
| 493 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 494 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-05.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 495 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 496 | <!--- TEST |
| 497 | I'm sleeping 0 ... |
| 498 | I'm sleeping 1 ... |
| 499 | I'm sleeping 2 ... |
| 500 | main: I'm tired of waiting! |
| 501 | I'm running finally |
| 502 | And I've just delayed for 1 sec because I'm non-cancellable |
| 503 | main: Now I can quit. |
| 504 | --> |
| 505 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 506 | ### Timeout |
| 507 | |
| 508 | The most obvious reason to cancel coroutine execution in practice, |
| 509 | is because its execution time has exceeded some timeout. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 510 | While you can manually track the reference to the corresponding [Job] and launch a separate coroutine to cancel |
| 511 | the tracked one after delay, there is a ready to use [withTimeout] function that does it. |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 512 | Look at the following example: |
| 513 | |
| 514 | ```kotlin |
| 515 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 516 | withTimeout(1300L) { |
| 517 | repeat(1000) { i -> |
| 518 | println("I'm sleeping $i ...") |
| 519 | delay(500L) |
| 520 | } |
| 521 | } |
| 522 | } |
| 523 | ``` |
| 524 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 525 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-06.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 526 | |
| 527 | It produces the following output: |
| 528 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 529 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 530 | I'm sleeping 0 ... |
| 531 | I'm sleeping 1 ... |
| 532 | I'm sleeping 2 ... |
| 533 | Exception in thread "main" java.util.concurrent.CancellationException: Timed out waiting for 1300 MILLISECONDS |
| 534 | ``` |
| 535 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 536 | <!--- TEST STARTS_WITH --> |
| 537 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 538 | We have not seen the [CancellationException] stack trace printed on the console before. That is because |
Roman Elizarov | 7c864d8 | 2017-02-27 10:17:50 +0300 | [diff] [blame] | 539 | inside a cancelled coroutine `CancellationException` is considered to be a normal reason for coroutine completion. |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 540 | However, in this example we have used `withTimeout` right inside the `main` function. |
| 541 | |
| 542 | Because cancellation is just an exception, all the resources will be closed in a usual way. |
| 543 | You can wrap the code with timeout in `try {...} catch (e: CancellationException) {...}` block if |
| 544 | you need to do some additional action specifically on timeout. |
| 545 | |
| 546 | ## Composing suspending functions |
| 547 | |
| 548 | This section covers various approaches to composition of suspending functions. |
| 549 | |
| 550 | ### Sequential by default |
| 551 | |
| 552 | Assume that we have two suspending functions defined elsewhere that do something useful like some kind of |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 553 | remote service call or computation. We just pretend they are useful, but actually each one just |
| 554 | delays for a second for the purpose of this example: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 555 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 556 | <!--- INCLUDE .*/example-compose-([0-9]+).kt |
| 557 | import kotlin.system.measureTimeMillis |
| 558 | --> |
| 559 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 560 | ```kotlin |
| 561 | suspend fun doSomethingUsefulOne(): Int { |
| 562 | delay(1000L) // pretend we are doing something useful here |
| 563 | return 13 |
| 564 | } |
| 565 | |
| 566 | suspend fun doSomethingUsefulTwo(): Int { |
| 567 | delay(1000L) // pretend we are doing something useful here, too |
| 568 | return 29 |
| 569 | } |
| 570 | ``` |
| 571 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 572 | <!--- INCLUDE .*/example-compose-([0-9]+).kt --> |
| 573 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 574 | What do we do if need to invoke them _sequentially_ -- first `doSomethingUsefulOne` _and then_ |
| 575 | `doSomethingUsefulTwo` and compute the sum of their results? |
| 576 | In practise we do this if we use the results of the first function to make a decision on whether we need |
| 577 | to invoke the second one or to decide on how to invoke it. |
| 578 | |
| 579 | We just use a normal sequential invocation, because the code in the coroutine, just like in the regular |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 580 | code, is _sequential_ by default. The following example demonstrates it by measuring the total |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 581 | time it takes to execute both suspending functions: |
| 582 | |
| 583 | ```kotlin |
| 584 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 585 | val time = measureTimeMillis { |
| 586 | val one = doSomethingUsefulOne() |
| 587 | val two = doSomethingUsefulTwo() |
| 588 | println("The answer is ${one + two}") |
| 589 | } |
| 590 | println("Completed in $time ms") |
| 591 | } |
| 592 | ``` |
| 593 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 594 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-01.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 595 | |
| 596 | It produces something like this: |
| 597 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 598 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 599 | The answer is 42 |
| 600 | Completed in 2017 ms |
| 601 | ``` |
| 602 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 603 | <!--- TEST FLEXIBLE_TIME --> |
| 604 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 605 | ### Concurrent using async |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 606 | |
| 607 | What if there are no dependencies between invocation of `doSomethingUsefulOne` and `doSomethingUsefulTwo` and |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 608 | we want to get the answer faster, by doing both _concurrently_? This is where [async] comes to help. |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 609 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 610 | Conceptually, [async] is just like [launch]. It starts a separate coroutine which is a light-weight thread |
| 611 | that works concurrently with all the other coroutines. The difference is that `launch` returns a [Job] and |
| 612 | does not carry any resulting value, while `async` returns a [Deferred] -- a light-weight non-blocking future |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 613 | that represents a promise to provide a result later. You can use `.await()` on a deferred value to get its eventual result, |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 614 | but `Deferred` is also a `Job`, so you can cancel it if needed. |
| 615 | |
| 616 | ```kotlin |
| 617 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 618 | val time = measureTimeMillis { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 619 | val one = async(CommonPool) { doSomethingUsefulOne() } |
| 620 | val two = async(CommonPool) { doSomethingUsefulTwo() } |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 621 | println("The answer is ${one.await() + two.await()}") |
| 622 | } |
| 623 | println("Completed in $time ms") |
| 624 | } |
| 625 | ``` |
| 626 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 627 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-02.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 628 | |
| 629 | It produces something like this: |
| 630 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 631 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 632 | The answer is 42 |
| 633 | Completed in 1017 ms |
| 634 | ``` |
| 635 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 636 | <!--- TEST FLEXIBLE_TIME --> |
| 637 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 638 | This is twice as fast, because we have concurrent execution of two coroutines. |
| 639 | Note, that concurrency with coroutines is always explicit. |
| 640 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 641 | ### Lazily started async |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 642 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 643 | There is a laziness option to [async] with `start = false` parameter. |
| 644 | It starts coroutine only when its result is needed by some |
| 645 | [await][Deferred.await] or if a [start][Job.start] function |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 646 | is invoked. Run the following example that differs from the previous one only by this option: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 647 | |
| 648 | ```kotlin |
| 649 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 650 | val time = measureTimeMillis { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 651 | val one = async(CommonPool, start = false) { doSomethingUsefulOne() } |
| 652 | val two = async(CommonPool, start = false) { doSomethingUsefulTwo() } |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 653 | println("The answer is ${one.await() + two.await()}") |
| 654 | } |
| 655 | println("Completed in $time ms") |
| 656 | } |
| 657 | ``` |
| 658 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 659 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-03.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 660 | |
| 661 | It produces something like this: |
| 662 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 663 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 664 | The answer is 42 |
| 665 | Completed in 2017 ms |
| 666 | ``` |
| 667 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 668 | <!--- TEST FLEXIBLE_TIME --> |
| 669 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 670 | So, we are back to sequential execution, because we _first_ start and await for `one`, _and then_ start and await |
| 671 | for `two`. It is not the intended use-case for laziness. It is designed as a replacement for |
| 672 | the standard `lazy` function in cases when computation of the value involves suspending functions. |
| 673 | |
| 674 | ### Async-style functions |
| 675 | |
| 676 | We can define async-style functions that invoke `doSomethingUsefulOne` and `doSomethingUsefulTwo` |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 677 | _asynchronously_ using [async] coroutine builder. It is a good style to name such functions with |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 678 | either "async" prefix of "Async" suffix to highlight the fact that they only start asynchronous |
| 679 | computation and one needs to use the resulting deferred value to get the result. |
| 680 | |
| 681 | ```kotlin |
| 682 | // The result type of asyncSomethingUsefulOne is Deferred<Int> |
| 683 | fun asyncSomethingUsefulOne() = async(CommonPool) { |
| 684 | doSomethingUsefulOne() |
| 685 | } |
| 686 | |
| 687 | // The result type of asyncSomethingUsefulTwo is Deferred<Int> |
| 688 | fun asyncSomethingUsefulTwo() = async(CommonPool) { |
| 689 | doSomethingUsefulTwo() |
| 690 | } |
| 691 | ``` |
| 692 | |
| 693 | Note, that these `asyncXXX` function are **not** _suspending_ functions. They can be used from anywhere. |
| 694 | However, their use always implies asynchronous (here meaning _concurrent_) execution of their action |
| 695 | with the invoking code. |
| 696 | |
| 697 | The following example shows their use outside of coroutine: |
| 698 | |
| 699 | ```kotlin |
| 700 | // note, that we don't have `runBlocking` to the right of `main` in this example |
| 701 | fun main(args: Array<String>) { |
| 702 | val time = measureTimeMillis { |
| 703 | // we can initiate async actions outside of a coroutine |
| 704 | val one = asyncSomethingUsefulOne() |
| 705 | val two = asyncSomethingUsefulTwo() |
| 706 | // but waiting for a result must involve either suspending or blocking. |
| 707 | // here we use `runBlocking { ... }` to block the main thread while waiting for the result |
| 708 | runBlocking { |
| 709 | println("The answer is ${one.await() + two.await()}") |
| 710 | } |
| 711 | } |
| 712 | println("Completed in $time ms") |
| 713 | } |
| 714 | ``` |
| 715 | |
| 716 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-04.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 717 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 718 | <!--- TEST FLEXIBLE_TIME |
| 719 | The answer is 42 |
| 720 | Completed in 1085 ms |
| 721 | --> |
| 722 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 723 | ## Coroutine context and dispatchers |
| 724 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 725 | We've already seen `launch(CommonPool) {...}`, `async(CommonPool) {...}`, `run(NonCancellable) {...}`, etc. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 726 | In these code snippets [CommonPool] and [NonCancellable] are _coroutine contexts_. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 727 | This section covers other available choices. |
| 728 | |
| 729 | ### Dispatchers and threads |
| 730 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 731 | Coroutine context includes a [_coroutine dispatcher_][CoroutineDispatcher] which determines what thread or threads |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 732 | the corresponding coroutine uses for its execution. Coroutine dispatcher can confine coroutine execution |
| 733 | to a specific thread, dispatch it to a thread pool, or let it run unconfined. Try the following example: |
| 734 | |
| 735 | ```kotlin |
| 736 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 737 | val jobs = arrayListOf<Job>() |
| 738 | jobs += launch(Unconfined) { // not confined -- will work with main thread |
| 739 | println(" 'Unconfined': I'm working in thread ${Thread.currentThread().name}") |
| 740 | } |
| 741 | jobs += launch(context) { // context of the parent, runBlocking coroutine |
| 742 | println(" 'context': I'm working in thread ${Thread.currentThread().name}") |
| 743 | } |
| 744 | jobs += launch(CommonPool) { // will get dispatched to ForkJoinPool.commonPool (or equivalent) |
| 745 | println(" 'CommonPool': I'm working in thread ${Thread.currentThread().name}") |
| 746 | } |
| 747 | jobs += launch(newSingleThreadContext("MyOwnThread")) { // will get its own new thread |
| 748 | println(" 'newSTC': I'm working in thread ${Thread.currentThread().name}") |
| 749 | } |
| 750 | jobs.forEach { it.join() } |
| 751 | } |
| 752 | ``` |
| 753 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 754 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-01.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 755 | |
| 756 | It produces the following output (maybe in different order): |
| 757 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 758 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 759 | 'Unconfined': I'm working in thread main |
| 760 | 'CommonPool': I'm working in thread ForkJoinPool.commonPool-worker-1 |
| 761 | 'newSTC': I'm working in thread MyOwnThread |
| 762 | 'context': I'm working in thread main |
| 763 | ``` |
| 764 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 765 | <!--- TEST LINES_START_UNORDERED --> |
| 766 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 767 | The difference between parent [context][CoroutineScope.context] and [Unconfined] context will be shown later. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 768 | |
| 769 | ### Unconfined vs confined dispatcher |
| 770 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 771 | The [Unconfined] coroutine dispatcher starts coroutine in the caller thread, but only until the |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 772 | first suspension point. After suspension it resumes in the thread that is fully determined by the |
| 773 | suspending function that was invoked. Unconfined dispatcher is appropriate when coroutine does not |
| 774 | consume CPU time nor updates any shared data (like UI) that is confined to a specific thread. |
| 775 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 776 | On the other side, [context][CoroutineScope.context] property that is available inside the block of any coroutine |
| 777 | via [CoroutineScope] interface, is a reference to a context of this particular coroutine. |
| 778 | This way, a parent context can be inherited. The default context of [runBlocking], in particular, |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 779 | is confined to be invoker thread, so inheriting it has the effect of confining execution to |
| 780 | this thread with a predictable FIFO scheduling. |
| 781 | |
| 782 | ```kotlin |
| 783 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 784 | val jobs = arrayListOf<Job>() |
| 785 | jobs += launch(Unconfined) { // not confined -- will work with main thread |
| 786 | println(" 'Unconfined': I'm working in thread ${Thread.currentThread().name}") |
| 787 | delay(1000) |
| 788 | println(" 'Unconfined': After delay in thread ${Thread.currentThread().name}") |
| 789 | } |
| 790 | jobs += launch(context) { // context of the parent, runBlocking coroutine |
| 791 | println(" 'context': I'm working in thread ${Thread.currentThread().name}") |
| 792 | delay(1000) |
| 793 | println(" 'context': After delay in thread ${Thread.currentThread().name}") |
| 794 | } |
| 795 | jobs.forEach { it.join() } |
| 796 | } |
| 797 | ``` |
| 798 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 799 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-contest-02.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 800 | |
| 801 | Produces the output: |
| 802 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 803 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 804 | 'Unconfined': I'm working in thread main |
| 805 | 'context': I'm working in thread main |
| 806 | 'Unconfined': After delay in thread kotlinx.coroutines.ScheduledExecutor |
| 807 | 'context': After delay in thread main |
| 808 | ``` |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 809 | |
| 810 | <!--- TEST LINES_START --> |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 811 | |
Roman Elizarov | 7c864d8 | 2017-02-27 10:17:50 +0300 | [diff] [blame] | 812 | So, the coroutine that had inherited `context` of `runBlocking {...}` continues to execute in the `main` thread, |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 813 | while the unconfined one had resumed in the scheduler thread that [delay] function is using. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 814 | |
| 815 | ### Debugging coroutines and threads |
| 816 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 817 | Coroutines can suspend on one thread and resume on another thread with [Unconfined] dispatcher or |
| 818 | with a multi-threaded dispatcher like [CommonPool]. Even with a single-threaded dispatcher it might be hard to |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 819 | figure out what coroutine was doing what, where, and when. The common approach to debugging applications with |
| 820 | threads is to print the thread name in the log file on each log statement. This feature is universally supported |
| 821 | by logging frameworks. When using coroutines, the thread name alone does not give much of a context, so |
| 822 | `kotlinx.coroutines` includes debugging facilities to make it easier. |
| 823 | |
| 824 | Run the following code with `-Dkotlinx.coroutines.debug` JVM option: |
| 825 | |
| 826 | ```kotlin |
| 827 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 828 | |
| 829 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 830 | val a = async(context) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 831 | log("I'm computing a piece of the answer") |
| 832 | 6 |
| 833 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 834 | val b = async(context) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 835 | log("I'm computing another piece of the answer") |
| 836 | 7 |
| 837 | } |
| 838 | log("The answer is ${a.await() * b.await()}") |
| 839 | } |
| 840 | ``` |
| 841 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 842 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-03.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 843 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 844 | There are three coroutines. The main coroutine (#1) -- `runBlocking` one, |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 845 | and two coroutines computing deferred values `a` (#2) and `b` (#3). |
| 846 | They are all executing in the context of `runBlocking` and are confined to the main thread. |
| 847 | The output of this code is: |
| 848 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 849 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 850 | [main @coroutine#2] I'm computing a piece of the answer |
| 851 | [main @coroutine#3] I'm computing another piece of the answer |
| 852 | [main @coroutine#1] The answer is 42 |
| 853 | ``` |
| 854 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 855 | <!--- TEST --> |
| 856 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 857 | The `log` function prints the name of the thread in square brackets and you can see, that it is the `main` |
| 858 | thread, but the identifier of the currently executing coroutine is appended to it. This identifier |
| 859 | is consecutively assigned to all created coroutines when debugging mode is turned on. |
| 860 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 861 | You can read more about debugging facilities in the documentation for [newCoroutineContext] function. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 862 | |
| 863 | ### Jumping between threads |
| 864 | |
| 865 | Run the following code with `-Dkotlinx.coroutines.debug` JVM option: |
| 866 | |
| 867 | ```kotlin |
| 868 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 869 | |
| 870 | fun main(args: Array<String>) { |
| 871 | val ctx1 = newSingleThreadContext("Ctx1") |
| 872 | val ctx2 = newSingleThreadContext("Ctx2") |
| 873 | runBlocking(ctx1) { |
| 874 | log("Started in ctx1") |
| 875 | run(ctx2) { |
| 876 | log("Working in ctx2") |
| 877 | } |
| 878 | log("Back to ctx1") |
| 879 | } |
| 880 | } |
| 881 | ``` |
| 882 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 883 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-04.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 884 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 885 | It demonstrates two new techniques. One is using [runBlocking] with an explicitly specified context, and |
| 886 | the second one is using [run] function to change a context of a coroutine while still staying in the |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 887 | same coroutine as you can see in the output below: |
| 888 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 889 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 890 | [Ctx1 @coroutine#1] Started in ctx1 |
| 891 | [Ctx2 @coroutine#1] Working in ctx2 |
| 892 | [Ctx1 @coroutine#1] Back to ctx1 |
| 893 | ``` |
| 894 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 895 | <!--- TEST --> |
| 896 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 897 | ### Job in the context |
| 898 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 899 | The coroutine [Job] is part of its context. The coroutine can retrieve it from its own context |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 900 | using `context[Job]` expression: |
| 901 | |
| 902 | ```kotlin |
| 903 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 904 | println("My job is ${context[Job]}") |
| 905 | } |
| 906 | ``` |
| 907 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 908 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-05.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 909 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 910 | It produces somethine like |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 911 | |
| 912 | ``` |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 913 | My job is BlockingCoroutine{Active}@65ae6ba4 |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 914 | ``` |
| 915 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 916 | <!--- TEST lines.size == 1 && lines[0].startsWith("My job is BlockingCoroutine{Active}@") --> |
| 917 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 918 | So, [isActive][CoroutineScope.isActive] in [CoroutineScope] is just a convenient shortcut for `context[Job]!!.isActive`. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 919 | |
| 920 | ### Children of a coroutine |
| 921 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 922 | When [context][CoroutineScope.context] of a coroutine is used to launch another coroutine, |
| 923 | the [Job] of the new coroutine becomes |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 924 | a _child_ of the parent coroutine's job. When the parent coroutine is cancelled, all its children |
| 925 | are recursively cancelled, too. |
| 926 | |
| 927 | ```kotlin |
| 928 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 929 | // start a coroutine to process some kind of incoming request |
| 930 | val request = launch(CommonPool) { |
| 931 | // it spawns two other jobs, one with its separate context |
| 932 | val job1 = launch(CommonPool) { |
| 933 | println("job1: I have my own context and execute independently!") |
| 934 | delay(1000) |
| 935 | println("job1: I am not affected by cancellation of the request") |
| 936 | } |
| 937 | // and the other inherits the parent context |
| 938 | val job2 = launch(context) { |
| 939 | println("job2: I am a child of the request coroutine") |
| 940 | delay(1000) |
| 941 | println("job2: I will not execute this line if my parent request is cancelled") |
| 942 | } |
| 943 | // request completes when both its sub-jobs complete: |
| 944 | job1.join() |
| 945 | job2.join() |
| 946 | } |
| 947 | delay(500) |
| 948 | request.cancel() // cancel processing of the request |
| 949 | delay(1000) // delay a second to see what happens |
| 950 | println("main: Who has survived request cancellation?") |
| 951 | } |
| 952 | ``` |
| 953 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 954 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-06.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 955 | |
| 956 | The output of this code is: |
| 957 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 958 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 959 | job1: I have my own context and execute independently! |
| 960 | job2: I am a child of the request coroutine |
| 961 | job1: I am not affected by cancellation of the request |
| 962 | main: Who has survived request cancellation? |
| 963 | ``` |
| 964 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 965 | <!--- TEST --> |
| 966 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 967 | ### Combining contexts |
| 968 | |
| 969 | Coroutine context can be combined using `+` operator. The context on the right-hand side replaces relevant entries |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 970 | of the context on the left-hand side. For example, a [Job] of the parent coroutine can be inherited, while |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 971 | its dispatcher replaced: |
| 972 | |
| 973 | ```kotlin |
| 974 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 975 | // start a coroutine to process some kind of incoming request |
| 976 | val request = launch(context) { // use the context of `runBlocking` |
| 977 | // spawns CPU-intensive child job in CommonPool !!! |
| 978 | val job = launch(context + CommonPool) { |
| 979 | println("job: I am a child of the request coroutine, but with a different dispatcher") |
| 980 | delay(1000) |
| 981 | println("job: I will not execute this line if my parent request is cancelled") |
| 982 | } |
| 983 | job.join() // request completes when its sub-job completes |
| 984 | } |
| 985 | delay(500) |
| 986 | request.cancel() // cancel processing of the request |
| 987 | delay(1000) // delay a second to see what happens |
| 988 | println("main: Who has survived request cancellation?") |
| 989 | } |
| 990 | ``` |
| 991 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 992 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-07.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 993 | |
| 994 | The expected outcome of this code is: |
| 995 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 996 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 997 | job: I am a child of the request coroutine, but with a different dispatcher |
| 998 | main: Who has survived request cancellation? |
| 999 | ``` |
| 1000 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1001 | <!--- TEST --> |
| 1002 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1003 | ### Naming coroutines for debugging |
| 1004 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1005 | Automatically assigned ids are good when coroutines log often and you just need to correlate log records |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1006 | coming from the same coroutine. However, when coroutine is tied to the processing of a specific request |
| 1007 | or doing some specific background task, it is better to name it explicitly for debugging purposes. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1008 | [CoroutineName] serves the same function as a thread name. It'll get displayed in the thread name that |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1009 | is executing this coroutine when debugging more is turned on. |
| 1010 | |
| 1011 | The following example demonstrates this concept: |
| 1012 | |
| 1013 | ```kotlin |
| 1014 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 1015 | |
| 1016 | fun main(args: Array<String>) = runBlocking(CoroutineName("main")) { |
| 1017 | log("Started main coroutine") |
| 1018 | // run two background value computations |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 1019 | val v1 = async(CommonPool + CoroutineName("v1coroutine")) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1020 | log("Computing v1") |
| 1021 | delay(500) |
| 1022 | 252 |
| 1023 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 1024 | val v2 = async(CommonPool + CoroutineName("v2coroutine")) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1025 | log("Computing v2") |
| 1026 | delay(1000) |
| 1027 | 6 |
| 1028 | } |
| 1029 | log("The answer for v1 / v2 = ${v1.await() / v2.await()}") |
| 1030 | } |
| 1031 | ``` |
| 1032 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 1033 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-08.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1034 | |
| 1035 | The output it produces with `-Dkotlinx.coroutines.debug` JVM option is similar to: |
| 1036 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1037 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1038 | [main @main#1] Started main coroutine |
| 1039 | [ForkJoinPool.commonPool-worker-1 @v1coroutine#2] Computing v1 |
| 1040 | [ForkJoinPool.commonPool-worker-2 @v2coroutine#3] Computing v2 |
| 1041 | [main @main#1] The answer for v1 / v2 = 42 |
| 1042 | ``` |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 1043 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1044 | <!--- TEST FLEXIBLE_THREAD --> |
| 1045 | |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1046 | ### Cancellation via explicit job |
| 1047 | |
| 1048 | Let us put our knowledge about contexts, children and jobs together. Assume that our application has |
| 1049 | an object with a lifecycle, but that object is not a coroutine. For example, we are writing an Android application |
| 1050 | and launch various coroutines in the context of an Android activity to perform asynchronous operations to fetch |
| 1051 | and update data, do animations, etc. All of these coroutines must be cancelled when activity is destroyed |
| 1052 | to avoid memory leaks. |
| 1053 | |
| 1054 | We can manage a lifecycle of our coroutines by creating an instance of [Job] that is tied to |
| 1055 | the lifecycle of our activity. A job instance is created using [Job()][Job.invoke] factory function |
| 1056 | as the following example shows. We need to make sure that all the coroutines are started |
| 1057 | with this job in their context and then a single invocation of [Job.cancel] terminates them all. |
| 1058 | |
| 1059 | ```kotlin |
| 1060 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1061 | val job = Job() // create a job object to manage our lifecycle |
| 1062 | // now launch ten coroutines for a demo, each working for a different time |
| 1063 | val coroutines = List(10) { i -> |
| 1064 | // they are all children of our job object |
| 1065 | launch(context + job) { // we use the context of main runBlocking thread, but with our own job object |
| 1066 | delay(i * 200L) // variable delay 0ms, 200ms, 400ms, ... etc |
| 1067 | println("Coroutine $i is done") |
| 1068 | } |
| 1069 | } |
| 1070 | println("Launched ${coroutines.size} coroutines") |
| 1071 | delay(500L) // delay for half a second |
| 1072 | println("Cancelling job!") |
| 1073 | job.cancel() // cancel our job.. !!! |
| 1074 | delay(1000L) // delay for more to see if our coroutines are still working |
| 1075 | } |
| 1076 | ``` |
| 1077 | |
| 1078 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-09.kt) |
| 1079 | |
| 1080 | The output of this example is: |
| 1081 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1082 | ```text |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1083 | Launched 10 coroutines |
| 1084 | Coroutine 0 is done |
| 1085 | Coroutine 1 is done |
| 1086 | Coroutine 2 is done |
| 1087 | Cancelling job! |
| 1088 | ``` |
| 1089 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1090 | <!--- TEST --> |
| 1091 | |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1092 | As you can see, only the first three coroutines had printed a message and the others were cancelled |
| 1093 | by a single invocation of `job.cancel()`. So all we need to do in our hypothetical Android |
| 1094 | application is to create a parent job object when activity is created, use it for child coroutines, |
| 1095 | and cancel it when activity is destroyed. |
| 1096 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1097 | ## Channels |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 1098 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1099 | Deferred values provide a convenient way to transfer a single value between coroutines. |
| 1100 | Channels provide a way to transfer a stream of values. |
| 1101 | |
| 1102 | <!--- INCLUDE .*/example-channel-([0-9]+).kt |
| 1103 | import kotlinx.coroutines.experimental.channels.* |
| 1104 | --> |
| 1105 | |
| 1106 | ### Channel basics |
| 1107 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1108 | A [Channel] is conceptually very similar to `BlockingQueue`. One key difference is that |
| 1109 | instead of a blocking `put` operation it has a suspending [send][SendChannel.send], and instead of |
| 1110 | a blocking `take` operation it has a suspending [receive][ReceiveChannel.receive]. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1111 | |
| 1112 | ```kotlin |
| 1113 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1114 | val channel = Channel<Int>() |
| 1115 | launch(CommonPool) { |
| 1116 | // this might be heavy CPU-consuming computation or async logic, we'll just send five squares |
| 1117 | for (x in 1..5) channel.send(x * x) |
| 1118 | } |
| 1119 | // here we print five received integers: |
| 1120 | repeat(5) { println(channel.receive()) } |
| 1121 | println("Done!") |
| 1122 | } |
| 1123 | ``` |
| 1124 | |
| 1125 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-01.kt) |
| 1126 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1127 | The output of this code is: |
| 1128 | |
| 1129 | ```text |
| 1130 | 1 |
| 1131 | 4 |
| 1132 | 9 |
| 1133 | 16 |
| 1134 | 25 |
| 1135 | Done! |
| 1136 | ``` |
| 1137 | |
| 1138 | <!--- TEST --> |
| 1139 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1140 | ### Closing and iteration over channels |
| 1141 | |
| 1142 | Unlike a queue, a channel can be closed to indicate that no more elements are coming. |
| 1143 | On the receiver side it is convenient to use a regular `for` loop to receive elements |
| 1144 | from the channel. |
| 1145 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1146 | Conceptually, a [close][SendChannel.close] is like sending a special close token to the channel. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1147 | The iteration stops as soon as this close token is received, so there is a guarantee |
| 1148 | that all previously sent elements before the close are received: |
| 1149 | |
| 1150 | ```kotlin |
| 1151 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1152 | val channel = Channel<Int>() |
| 1153 | launch(CommonPool) { |
| 1154 | for (x in 1..5) channel.send(x * x) |
| 1155 | channel.close() // we're done sending |
| 1156 | } |
| 1157 | // here we print received values using `for` loop (until the channel is closed) |
| 1158 | for (y in channel) println(y) |
| 1159 | println("Done!") |
| 1160 | } |
| 1161 | ``` |
| 1162 | |
| 1163 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-02.kt) |
| 1164 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1165 | <!--- TEST |
| 1166 | 1 |
| 1167 | 4 |
| 1168 | 9 |
| 1169 | 16 |
| 1170 | 25 |
| 1171 | Done! |
| 1172 | --> |
| 1173 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1174 | ### Building channel producers |
| 1175 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1176 | The pattern where a coroutine is producing a sequence of elements is quite common. |
| 1177 | This is a part of _producer-consumer_ pattern that is often found in concurrent code. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1178 | You could abstract such a producer into a function that takes channel as its parameter, but this goes contrary |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1179 | to common sense that results must be returned from functions. |
| 1180 | |
| 1181 | There is a convenience coroutine builder named [produce] that makes it easy to do it right: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1182 | |
| 1183 | ```kotlin |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1184 | fun produceSquares() = produce<Int>(CommonPool) { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1185 | for (x in 1..5) send(x * x) |
| 1186 | } |
| 1187 | |
| 1188 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1189 | val squares = produceSquares() |
| 1190 | for (y in squares) println(y) |
| 1191 | println("Done!") |
| 1192 | } |
| 1193 | ``` |
| 1194 | |
| 1195 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-03.kt) |
| 1196 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1197 | <!--- TEST |
| 1198 | 1 |
| 1199 | 4 |
| 1200 | 9 |
| 1201 | 16 |
| 1202 | 25 |
| 1203 | Done! |
| 1204 | --> |
| 1205 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1206 | ### Pipelines |
| 1207 | |
| 1208 | Pipeline is a pattern where one coroutine is producing, possibly infinite, stream of values: |
| 1209 | |
| 1210 | ```kotlin |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1211 | fun produceNumbers() = produce<Int>(CommonPool) { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1212 | var x = 1 |
| 1213 | while (true) send(x++) // infinite stream of integers starting from 1 |
| 1214 | } |
| 1215 | ``` |
| 1216 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1217 | And another coroutine or coroutines are consuming that stream, doing some processing, and producing some other results. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1218 | In the below example the numbers are just squared: |
| 1219 | |
| 1220 | ```kotlin |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1221 | fun square(numbers: ReceiveChannel<Int>) = produce<Int>(CommonPool) { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1222 | for (x in numbers) send(x * x) |
| 1223 | } |
| 1224 | ``` |
| 1225 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1226 | The main code starts and connects the whole pipeline: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1227 | |
| 1228 | ```kotlin |
| 1229 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1230 | val numbers = produceNumbers() // produces integers from 1 and on |
| 1231 | val squares = square(numbers) // squares integers |
| 1232 | for (i in 1..5) println(squares.receive()) // print first five |
| 1233 | println("Done!") // we are done |
| 1234 | squares.cancel() // need to cancel these coroutines in a larger app |
| 1235 | numbers.cancel() |
| 1236 | } |
| 1237 | ``` |
| 1238 | |
| 1239 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-04.kt) |
| 1240 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1241 | <!--- TEST |
| 1242 | 1 |
| 1243 | 4 |
| 1244 | 9 |
| 1245 | 16 |
| 1246 | 25 |
| 1247 | Done! |
| 1248 | --> |
| 1249 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1250 | We don't have to cancel these coroutines in this example app, because |
| 1251 | [coroutines are like daemon threads](#coroutines-are-like-daemon-threads), |
| 1252 | but in a larger app we'll need to stop our pipeline if we don't need it anymore. |
| 1253 | Alternatively, we could have run pipeline coroutines as |
| 1254 | [children of a coroutine](#children-of-a-coroutine). |
| 1255 | |
| 1256 | ### Prime numbers with pipeline |
| 1257 | |
Cedric Beust | fa0b28f | 2017-02-07 07:07:25 -0800 | [diff] [blame] | 1258 | Let's take pipelines to the extreme with an example that generates prime numbers using a pipeline |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1259 | of coroutines. We start with an infinite sequence of numbers. This time we introduce an |
| 1260 | explicit context parameter, so that caller can control where our coroutines run: |
| 1261 | |
| 1262 | <!--- INCLUDE kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-05.kt |
| 1263 | import kotlin.coroutines.experimental.CoroutineContext |
| 1264 | --> |
| 1265 | |
| 1266 | ```kotlin |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1267 | fun numbersFrom(context: CoroutineContext, start: Int) = produce<Int>(context) { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1268 | var x = start |
| 1269 | while (true) send(x++) // infinite stream of integers from start |
| 1270 | } |
| 1271 | ``` |
| 1272 | |
| 1273 | The following pipeline stage filters an incoming stream of numbers, removing all the numbers |
| 1274 | that are divisible by the given prime number: |
| 1275 | |
| 1276 | ```kotlin |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1277 | fun filter(context: CoroutineContext, numbers: ReceiveChannel<Int>, prime: Int) = produce<Int>(context) { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1278 | for (x in numbers) if (x % prime != 0) send(x) |
| 1279 | } |
| 1280 | ``` |
| 1281 | |
| 1282 | Now we build our pipeline by starting a stream of numbers from 2, taking a prime number from the current channel, |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 1283 | and launching new pipeline stage for each prime number found: |
| 1284 | |
| 1285 | ``` |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1286 | numbersFrom(2) -> filter(2) -> filter(3) -> filter(5) -> filter(7) ... |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 1287 | ``` |
| 1288 | |
| 1289 | The following example prints the first ten prime numbers, |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1290 | running the whole pipeline in the context of the main thread: |
| 1291 | |
| 1292 | ```kotlin |
| 1293 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1294 | var cur = numbersFrom(context, 2) |
| 1295 | for (i in 1..10) { |
| 1296 | val prime = cur.receive() |
| 1297 | println(prime) |
| 1298 | cur = filter(context, cur, prime) |
| 1299 | } |
| 1300 | } |
| 1301 | ``` |
| 1302 | |
| 1303 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-05.kt) |
| 1304 | |
| 1305 | The output of this code is: |
| 1306 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1307 | ```text |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1308 | 2 |
| 1309 | 3 |
| 1310 | 5 |
| 1311 | 7 |
| 1312 | 11 |
| 1313 | 13 |
| 1314 | 17 |
| 1315 | 19 |
| 1316 | 23 |
| 1317 | 29 |
| 1318 | ``` |
| 1319 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1320 | <!--- TEST --> |
| 1321 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1322 | Note, that you can build the same pipeline using `buildIterator` coroutine builder from the standard library. |
| 1323 | Replace `produce` with `buildIterator`, `send` with `yield`, `receive` with `next`, |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 1324 | `ReceiveChannel` with `Iterator`, and get rid of the context. You will not need `runBlocking` either. |
| 1325 | However, the benefit of a pipeline that uses channels as shown above is that it can actually use |
| 1326 | multiple CPU cores if you run it in [CommonPool] context. |
| 1327 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1328 | Anyway, this is an extremely impractical way to find prime numbers. In practice, pipelines do involve some |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 1329 | other suspending invocations (like asynchronous calls to remote services) and these pipelines cannot be |
| 1330 | built using `buildSeqeunce`/`buildIterator`, because they do not allow arbitrary suspension, unlike |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1331 | `produce` which is fully asynchronous. |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 1332 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1333 | ### Fan-out |
| 1334 | |
| 1335 | Multiple coroutines may receive from the same channel, distributing work between themselves. |
| 1336 | Let us start with a producer coroutine that is periodically producing integers |
| 1337 | (ten numbers per second): |
| 1338 | |
| 1339 | ```kotlin |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1340 | fun produceNumbers() = produce<Int>(CommonPool) { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1341 | var x = 1 // start from 1 |
| 1342 | while (true) { |
| 1343 | send(x++) // produce next |
| 1344 | delay(100) // wait 0.1s |
| 1345 | } |
| 1346 | } |
| 1347 | ``` |
| 1348 | |
| 1349 | Then we can have several processor coroutines. In this example, they just print their id and |
| 1350 | received number: |
| 1351 | |
| 1352 | ```kotlin |
| 1353 | fun launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch(CommonPool) { |
Roman Elizarov | ec9384c | 2017-03-02 22:09:08 +0300 | [diff] [blame^] | 1354 | for (x in channel) { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1355 | println("Processor #$id received $x") |
Roman Elizarov | ec9384c | 2017-03-02 22:09:08 +0300 | [diff] [blame^] | 1356 | } |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1357 | } |
| 1358 | ``` |
| 1359 | |
| 1360 | Now let us launch five processors and let them work for a second. See what happens: |
| 1361 | |
| 1362 | ```kotlin |
| 1363 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1364 | val producer = produceNumbers() |
| 1365 | repeat(5) { launchProcessor(it, producer) } |
| 1366 | delay(1000) |
| 1367 | producer.cancel() // cancel producer coroutine and thus kill them all |
| 1368 | } |
| 1369 | ``` |
| 1370 | |
| 1371 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-06.kt) |
| 1372 | |
| 1373 | The output will be similar to the the following one, albeit the processor ids that receive |
| 1374 | each specific integer may be different: |
| 1375 | |
| 1376 | ``` |
| 1377 | Processor #2 received 1 |
| 1378 | Processor #4 received 2 |
| 1379 | Processor #0 received 3 |
| 1380 | Processor #1 received 4 |
| 1381 | Processor #3 received 5 |
| 1382 | Processor #2 received 6 |
| 1383 | Processor #4 received 7 |
| 1384 | Processor #0 received 8 |
| 1385 | Processor #1 received 9 |
| 1386 | Processor #3 received 10 |
| 1387 | ``` |
| 1388 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1389 | <!--- TEST lines.size == 10 && lines.withIndex().all { (i, line) -> line.startsWith("Processor #") && line.endsWith(" received ${i + 1}") } --> |
| 1390 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1391 | Note, that cancelling a producer coroutine closes its channel, thus eventually terminating iteration |
| 1392 | over the channel that processor coroutines are doing. |
| 1393 | |
| 1394 | ### Fan-in |
| 1395 | |
| 1396 | Multiple coroutines may send to the same channel. |
| 1397 | For example, let us have a channel of strings, and a suspending function that |
| 1398 | repeatedly sends a specified string to this channel with a specified delay: |
| 1399 | |
| 1400 | ```kotlin |
| 1401 | suspend fun sendString(channel: SendChannel<String>, s: String, time: Long) { |
| 1402 | while (true) { |
| 1403 | delay(time) |
| 1404 | channel.send(s) |
| 1405 | } |
| 1406 | } |
| 1407 | ``` |
| 1408 | |
Cedric Beust | fa0b28f | 2017-02-07 07:07:25 -0800 | [diff] [blame] | 1409 | Now, let us see what happens if we launch a couple of coroutines sending strings |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1410 | (in this example we launch them in the context of the main thread): |
| 1411 | |
| 1412 | ```kotlin |
| 1413 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1414 | val channel = Channel<String>() |
| 1415 | launch(context) { sendString(channel, "foo", 200L) } |
| 1416 | launch(context) { sendString(channel, "BAR!", 500L) } |
| 1417 | repeat(6) { // receive first six |
| 1418 | println(channel.receive()) |
| 1419 | } |
| 1420 | } |
| 1421 | ``` |
| 1422 | |
| 1423 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-07.kt) |
| 1424 | |
| 1425 | The output is: |
| 1426 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1427 | ```text |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1428 | foo |
| 1429 | foo |
| 1430 | BAR! |
| 1431 | foo |
| 1432 | foo |
| 1433 | BAR! |
| 1434 | ``` |
| 1435 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1436 | <!--- TEST --> |
| 1437 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1438 | ### Buffered channels |
| 1439 | |
| 1440 | The channels shown so far had no buffer. Unbuffered channels transfer elements when sender and receiver |
| 1441 | meet each other (aka rendezvous). If send is invoked first, then it is suspended until receive is invoked, |
| 1442 | if receive is invoked first, it is suspended until send is invoked. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1443 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1444 | Both [Channel()][Channel.invoke] factory function and [produce] builder take an optional `capacity` parameter to |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1445 | specify _buffer size_. Buffer allows senders to send multiple elements before suspending, |
| 1446 | similar to the `BlockingQueue` with a specified capacity, which blocks when buffer is full. |
| 1447 | |
| 1448 | Take a look at the behavior of the following code: |
| 1449 | |
| 1450 | ```kotlin |
| 1451 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1452 | val channel = Channel<Int>(4) // create buffered channel |
| 1453 | launch(context) { // launch sender coroutine |
| 1454 | repeat(10) { |
| 1455 | println("Sending $it") // print before sending each element |
| 1456 | channel.send(it) // will suspend when buffer is full |
| 1457 | } |
| 1458 | } |
| 1459 | // don't receive anything... just wait.... |
| 1460 | delay(1000) |
| 1461 | } |
| 1462 | ``` |
| 1463 | |
| 1464 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-08.kt) |
| 1465 | |
| 1466 | It prints "sending" _five_ times using a buffered channel with capacity of _four_: |
| 1467 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1468 | ```text |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1469 | Sending 0 |
| 1470 | Sending 1 |
| 1471 | Sending 2 |
| 1472 | Sending 3 |
| 1473 | Sending 4 |
| 1474 | ``` |
| 1475 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1476 | <!--- TEST --> |
| 1477 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1478 | The first four elements are added to the buffer and the sender suspends when trying to send the fifth one. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1479 | |
Roman Elizarov | b0517ba | 2017-02-27 14:03:14 +0300 | [diff] [blame] | 1480 | |
| 1481 | ### Channels are fair |
| 1482 | |
| 1483 | Send and receive operations to channels are _fair_ with respect to the order of their invocation from |
| 1484 | multiple coroutines. They are served in first-in first-out order, e.g. the first coroutine to invoke `receive` |
| 1485 | gets the element. In the following example two coroutines "ping" and "pong" are |
| 1486 | receiving the "ball" object from the shared "table" channel. |
| 1487 | |
| 1488 | ```kotlin |
| 1489 | data class Ball(var hits: Int) |
| 1490 | |
| 1491 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1492 | val table = Channel<Ball>() // a shared table |
| 1493 | launch(context) { player("ping", table) } |
| 1494 | launch(context) { player("pong", table) } |
| 1495 | table.send(Ball(0)) // serve the ball |
| 1496 | delay(1000) // delay 1 second |
| 1497 | table.receive() // game over, grab the ball |
| 1498 | } |
| 1499 | |
| 1500 | suspend fun player(name: String, table: Channel<Ball>) { |
| 1501 | for (ball in table) { // receive the ball in a loop |
| 1502 | ball.hits++ |
| 1503 | println("$name $ball") |
| 1504 | delay(200) // wait a bit |
| 1505 | table.send(ball) // send the ball back |
| 1506 | } |
| 1507 | } |
| 1508 | ``` |
| 1509 | |
| 1510 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-09.kt) |
| 1511 | |
| 1512 | The "ping" coroutine is started first, so it is the first one to receive the ball. Even though "ping" |
| 1513 | coroutine immediately starts receiving the ball again after sending it back to the table, the ball gets |
| 1514 | received by the "pong" coroutine, because it was already waiting for it: |
| 1515 | |
| 1516 | ```text |
| 1517 | ping Ball(hits=1) |
| 1518 | pong Ball(hits=2) |
| 1519 | ping Ball(hits=3) |
| 1520 | pong Ball(hits=4) |
| 1521 | ping Ball(hits=5) |
| 1522 | pong Ball(hits=6) |
| 1523 | ``` |
| 1524 | |
| 1525 | <!--- TEST --> |
| 1526 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1527 | ## Shared mutable state and concurrency |
| 1528 | |
| 1529 | Coroutines can be executed concurrently using a multi-threaded dispatcher like [CommonPool]. It presents |
| 1530 | all the usual concurrency problems. The main problem being synchronization of access to **shared mutable state**. |
| 1531 | Some solutions to this problem in the land of coroutines are similar to the solutions in the multi-threaded world, |
| 1532 | but others are unique. |
| 1533 | |
| 1534 | ### The problem |
| 1535 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1536 | Let us launch a thousand coroutines all doing the same action thousand times (for a total of a million executions). |
| 1537 | We'll also measure their completion time for further comparisons: |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1538 | |
| 1539 | <!--- INCLUDE .*/example-sync-([0-9]+).kt |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1540 | import kotlin.coroutines.experimental.CoroutineContext |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1541 | import kotlin.system.measureTimeMillis |
| 1542 | --> |
| 1543 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1544 | <!--- INCLUDE .*/example-sync-03.kt |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1545 | import java.util.concurrent.atomic.AtomicInteger |
| 1546 | --> |
| 1547 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1548 | <!--- INCLUDE .*/example-sync-06.kt |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1549 | import kotlinx.coroutines.experimental.sync.Mutex |
| 1550 | --> |
| 1551 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1552 | <!--- INCLUDE .*/example-sync-07.kt |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1553 | import kotlinx.coroutines.experimental.channels.* |
| 1554 | --> |
| 1555 | |
| 1556 | ```kotlin |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1557 | suspend fun massiveRun(context: CoroutineContext, action: suspend () -> Unit) { |
| 1558 | val n = 1000 // number of coroutines to launch |
| 1559 | val k = 1000 // times an action is repeated by each coroutine |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1560 | val time = measureTimeMillis { |
| 1561 | val jobs = List(n) { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1562 | launch(context) { |
| 1563 | repeat(k) { action() } |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1564 | } |
| 1565 | } |
| 1566 | jobs.forEach { it.join() } |
| 1567 | } |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1568 | println("Completed ${n * k} actions in $time ms") |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1569 | } |
| 1570 | ``` |
| 1571 | |
| 1572 | <!--- INCLUDE .*/example-sync-([0-9]+).kt --> |
| 1573 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1574 | We start with a very simple action that increments a shared mutable variable using |
| 1575 | multi-threaded [CommonPool] context. |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1576 | |
| 1577 | ```kotlin |
| 1578 | var counter = 0 |
| 1579 | |
| 1580 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1581 | massiveRun(CommonPool) { |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1582 | counter++ |
| 1583 | } |
| 1584 | println("Counter = $counter") |
| 1585 | } |
| 1586 | ``` |
| 1587 | |
| 1588 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-01.kt) |
| 1589 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1590 | <!--- TEST LINES_START |
| 1591 | Completed 1000000 actions in |
| 1592 | Counter = |
| 1593 | --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1594 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1595 | What does it print at the end? It is highly unlikely to ever print "Counter = 1000000", because a thousand coroutines |
| 1596 | increment the `counter` concurrently from multiple threads without any synchronization. |
| 1597 | |
| 1598 | ### Volatiles are of no help |
| 1599 | |
| 1600 | There is common misconception that making a variable `volatile` solves concurrency problem. Let us try it: |
| 1601 | |
| 1602 | ```kotlin |
| 1603 | @Volatile // in Kotlin `volatile` is an annotation |
| 1604 | var counter = 0 |
| 1605 | |
| 1606 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1607 | massiveRun(CommonPool) { |
| 1608 | counter++ |
| 1609 | } |
| 1610 | println("Counter = $counter") |
| 1611 | } |
| 1612 | ``` |
| 1613 | |
| 1614 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-02.kt) |
| 1615 | |
| 1616 | <!--- TEST LINES_START |
| 1617 | Completed 1000000 actions in |
| 1618 | Counter = |
| 1619 | --> |
| 1620 | |
| 1621 | This code works slower, but we still don't get "Counter = 1000000" at the end, because volatile variables guarantee |
| 1622 | linearizable (this is a technical term for "atomic") reads and writes to the corresponding variable, but |
| 1623 | do not provide atomicity of larger actions (increment in our case). |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1624 | |
| 1625 | ### Thread-safe data structures |
| 1626 | |
| 1627 | The general solution that works both for threads and for coroutines is to use a thread-safe (aka synchronized, |
| 1628 | linearizable, or atomic) data structure that provides all the necessarily synchronization for the corresponding |
| 1629 | operations that needs to be performed on a shared state. |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1630 | In the case of a simple counter we can use `AtomicInteger` class which has atomic `incrementAndGet` operations: |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1631 | |
| 1632 | ```kotlin |
| 1633 | var counter = AtomicInteger() |
| 1634 | |
| 1635 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1636 | massiveRun(CommonPool) { |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1637 | counter.incrementAndGet() |
| 1638 | } |
| 1639 | println("Counter = ${counter.get()}") |
| 1640 | } |
| 1641 | ``` |
| 1642 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1643 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-03.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1644 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1645 | <!--- TEST ARBITRARY_TIME |
| 1646 | Completed 1000000 actions in xxx ms |
| 1647 | Counter = 1000000 |
| 1648 | --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1649 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1650 | This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other |
| 1651 | standard data structures and basic operations on them. However, it does not easily scale to complex |
| 1652 | state or to complex operations that do not have ready-to-use thread-safe implementations. |
| 1653 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1654 | ### Thread confinement fine-grained |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1655 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1656 | _Thread confinement_ is an approach to the problem of shared mutable state where all access to the particular shared |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1657 | state is confined to a single thread. It is typically used in UI applications, where all UI state is confined to |
| 1658 | the single event-dispatch/application thread. It is easy to apply with coroutines by using a |
| 1659 | single-threaded context: |
| 1660 | |
| 1661 | ```kotlin |
| 1662 | val counterContext = newSingleThreadContext("CounterContext") |
| 1663 | var counter = 0 |
| 1664 | |
| 1665 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1666 | massiveRun(CommonPool) { // run each coroutine in CommonPool |
| 1667 | run(counterContext) { // but confine each increment to the single-threaded context |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1668 | counter++ |
| 1669 | } |
| 1670 | } |
| 1671 | println("Counter = $counter") |
| 1672 | } |
| 1673 | ``` |
| 1674 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1675 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-04.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1676 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1677 | <!--- TEST ARBITRARY_TIME |
| 1678 | Completed 1000000 actions in xxx ms |
| 1679 | Counter = 1000000 |
| 1680 | --> |
| 1681 | |
| 1682 | This code works very slowly, because it does _fine-grained_ thread-confinement. Each individual increment switches |
| 1683 | from multi-threaded `CommonPool` context to the single-threaded context using [run] block. |
| 1684 | |
| 1685 | ### Thread confinement coarse-grained |
| 1686 | |
| 1687 | In practice, thread confinement is performed in large chunks, e.g. big pieces of state-updating business logic |
| 1688 | are confined to the single thread. The following example does it like that, running each coroutine in |
| 1689 | the single-threaded context to start with. |
| 1690 | |
| 1691 | ```kotlin |
| 1692 | val counterContext = newSingleThreadContext("CounterContext") |
| 1693 | var counter = 0 |
| 1694 | |
| 1695 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1696 | massiveRun(counterContext) { // run each coroutine in the single-threaded context |
| 1697 | counter++ |
| 1698 | } |
| 1699 | println("Counter = $counter") |
| 1700 | } |
| 1701 | ``` |
| 1702 | |
| 1703 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-05.kt) |
| 1704 | |
| 1705 | <!--- TEST ARBITRARY_TIME |
| 1706 | Completed 1000000 actions in xxx ms |
| 1707 | Counter = 1000000 |
| 1708 | --> |
| 1709 | |
| 1710 | This now works much faster and produces correct result. |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1711 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1712 | ### Mutual exclusion |
| 1713 | |
| 1714 | Mutual exclusion solution to the problem is to protect all modifications of the shared state with a _critical section_ |
| 1715 | that is never executed concurrently. In a blocking world you'd typically use `synchronized` or `ReentrantLock` for that. |
| 1716 | Coroutine's alternative is called [Mutex]. It has [lock][Mutex.lock] and [unlock][Mutex.unlock] functions to |
| 1717 | delimit a critical section. The key difference is that `Mutex.lock` is a suspending function. It does not block a thread. |
| 1718 | |
| 1719 | ```kotlin |
| 1720 | val mutex = Mutex() |
| 1721 | var counter = 0 |
| 1722 | |
| 1723 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1724 | massiveRun(CommonPool) { |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1725 | mutex.lock() |
| 1726 | try { counter++ } |
| 1727 | finally { mutex.unlock() } |
| 1728 | } |
| 1729 | println("Counter = $counter") |
| 1730 | } |
| 1731 | ``` |
| 1732 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1733 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-06.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1734 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1735 | <!--- TEST ARBITRARY_TIME |
| 1736 | Completed 1000000 actions in xxx ms |
| 1737 | Counter = 1000000 |
| 1738 | --> |
| 1739 | |
| 1740 | The locking in this example is fine-grained, so it pays the price. However, it is a good choice for some situations |
| 1741 | where you absolutely must modify some shared state periodically, but there is no natural thread that this state |
| 1742 | is confined to. |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1743 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1744 | ### Actors |
| 1745 | |
| 1746 | An actor is a combination of a coroutine, the state that is confined and is encapsulated into this coroutine, |
| 1747 | and a channel to communicate with other coroutines. A simple actor can be written as a function, |
| 1748 | but an actor with a complex state is better suited for a class. |
| 1749 | |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 1750 | There is an [actor] coroutine builder that conveniently combines actor's mailbox channel into its |
| 1751 | scope to receive messages from and combines the send channel into the resulting job object, so that a |
| 1752 | single reference to the actor can be carried around as its handle. |
| 1753 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1754 | ```kotlin |
| 1755 | // Message types for counterActor |
| 1756 | sealed class CounterMsg |
| 1757 | object IncCounter : CounterMsg() // one-way message to increment counter |
| 1758 | class GetCounter(val response: SendChannel<Int>) : CounterMsg() // a request with reply |
| 1759 | |
| 1760 | // This function launches a new counter actor |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 1761 | fun counterActor() = actor<CounterMsg>(CommonPool) { |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1762 | var counter = 0 // actor state |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 1763 | for (msg in channel) { // iterate over incoming messages |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1764 | when (msg) { |
| 1765 | is IncCounter -> counter++ |
| 1766 | is GetCounter -> msg.response.send(counter) |
| 1767 | } |
| 1768 | } |
| 1769 | } |
| 1770 | |
| 1771 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 1772 | val counter = counterActor() // create the actor |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1773 | massiveRun(CommonPool) { |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 1774 | counter.send(IncCounter) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1775 | } |
| 1776 | val response = Channel<Int>() |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 1777 | counter.send(GetCounter(response)) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1778 | println("Counter = ${response.receive()}") |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 1779 | counter.close() // shutdown the actor |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1780 | } |
| 1781 | ``` |
| 1782 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1783 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-07.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1784 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1785 | <!--- TEST ARBITRARY_TIME |
| 1786 | Completed 1000000 actions in xxx ms |
| 1787 | Counter = 1000000 |
| 1788 | --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1789 | |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 1790 | It does not matter (for correctness) what context the actor itself is executed in. An actor is |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 1791 | a coroutine and a coroutine is executed sequentially, so confinement of the state to the specific coroutine |
| 1792 | works as a solution to the problem of shared mutable state. |
| 1793 | |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 1794 | Actor is more efficient than locking under load, because in this case it always has work to do and it does not |
| 1795 | have to switch to a different context at all. |
| 1796 | |
| 1797 | > Note, that an [actor] coroutine builder is a dual of [produce] coroutine builder. An actor is associated |
| 1798 | with the channel that it receives messages from, while a producer is associated with the channel that it |
| 1799 | sends elements to. |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 1800 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1801 | ## Select expression |
| 1802 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1803 | Select expression makes it possible to await multiple suspending functions simultaneously and _select_ |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1804 | the first one that becomes available. |
| 1805 | |
| 1806 | <!--- INCLUDE .*/example-select-([0-9]+).kt |
| 1807 | import kotlinx.coroutines.experimental.channels.* |
| 1808 | import kotlinx.coroutines.experimental.selects.* |
| 1809 | --> |
| 1810 | |
| 1811 | ### Selecting from channels |
| 1812 | |
| 1813 | Let us have two channels of strings `fizz` and `buzz`. The `fizz` channel produces "Fizz" string every 300 ms: |
| 1814 | |
| 1815 | ```kotlin |
| 1816 | val fizz = produce<String>(CommonPool) { // produce using common thread pool |
| 1817 | while (true) { |
| 1818 | delay(300) |
| 1819 | send("Fizz") |
| 1820 | } |
| 1821 | } |
| 1822 | ``` |
| 1823 | |
| 1824 | And the `buzz` channel produces "Buzz!" string every 500 ms: |
| 1825 | |
| 1826 | ```kotlin |
| 1827 | val buzz = produce<String>(CommonPool) { |
| 1828 | while (true) { |
| 1829 | delay(500) |
| 1830 | send("Buzz!") |
| 1831 | } |
| 1832 | } |
| 1833 | ``` |
| 1834 | |
| 1835 | Using [receive][ReceiveChannel.receive] suspending function we can receive _either_ from one channel or the |
| 1836 | other. But [select] expression allows us to receive from _both_ simultaneously using its |
| 1837 | [onReceive][SelectBuilder.onReceive] clauses: |
| 1838 | |
| 1839 | ```kotlin |
| 1840 | suspend fun selectFizzBuzz() { |
| 1841 | select<Unit> { // <Unit> means that this select expression does not produce any result |
| 1842 | fizz.onReceive { value -> // this is the first select clause |
| 1843 | println("fizz -> '$value'") |
| 1844 | } |
| 1845 | buzz.onReceive { value -> // this is the second select clause |
| 1846 | println("buzz -> '$value'") |
| 1847 | } |
| 1848 | } |
| 1849 | } |
| 1850 | ``` |
| 1851 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1852 | Let us run it seven times: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1853 | |
| 1854 | ```kotlin |
| 1855 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1856 | repeat(7) { |
| 1857 | selectFizzBuzz() |
| 1858 | } |
| 1859 | } |
| 1860 | ``` |
| 1861 | |
| 1862 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-select-01.kt) |
| 1863 | |
| 1864 | The result of this code is: |
| 1865 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1866 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1867 | fizz -> 'Fizz' |
| 1868 | buzz -> 'Buzz!' |
| 1869 | fizz -> 'Fizz' |
| 1870 | fizz -> 'Fizz' |
| 1871 | buzz -> 'Buzz!' |
| 1872 | fizz -> 'Fizz' |
| 1873 | buzz -> 'Buzz!' |
| 1874 | ``` |
| 1875 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1876 | <!--- TEST --> |
| 1877 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1878 | ### Selecting on close |
| 1879 | |
| 1880 | The [onReceive][SelectBuilder.onReceive] clause in `select` fails when the channel is closed and the corresponding |
| 1881 | `select` throws an exception. We can use [onReceiveOrNull][SelectBuilder.onReceiveOrNull] clause to perform a |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1882 | specific action when the channel is closed. The following example also shows that `select` is an expression that returns |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1883 | the result of its selected clause: |
| 1884 | |
| 1885 | ```kotlin |
| 1886 | suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String = |
| 1887 | select<String> { |
| 1888 | a.onReceiveOrNull { value -> |
| 1889 | if (value == null) |
| 1890 | "Channel 'a' is closed" |
| 1891 | else |
| 1892 | "a -> '$value'" |
| 1893 | } |
| 1894 | b.onReceiveOrNull { value -> |
| 1895 | if (value == null) |
| 1896 | "Channel 'b' is closed" |
| 1897 | else |
| 1898 | "b -> '$value'" |
| 1899 | } |
| 1900 | } |
| 1901 | ``` |
| 1902 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1903 | Let's use it with channel `a` that produces "Hello" string four times and |
| 1904 | channel `b` that produces "World" four times: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1905 | |
| 1906 | ```kotlin |
| 1907 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1908 | // we are using the context of the main thread in this example for predictability ... |
| 1909 | val a = produce<String>(context) { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1910 | repeat(4) { send("Hello $it") } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1911 | } |
| 1912 | val b = produce<String>(context) { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1913 | repeat(4) { send("World $it") } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1914 | } |
| 1915 | repeat(8) { // print first eight results |
| 1916 | println(selectAorB(a, b)) |
| 1917 | } |
| 1918 | } |
| 1919 | ``` |
| 1920 | |
| 1921 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-select-02.kt) |
| 1922 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1923 | The result of this code is quite interesting, so we'll analyze it in mode detail: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1924 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1925 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1926 | a -> 'Hello 0' |
| 1927 | a -> 'Hello 1' |
| 1928 | b -> 'World 0' |
| 1929 | a -> 'Hello 2' |
| 1930 | a -> 'Hello 3' |
| 1931 | b -> 'World 1' |
| 1932 | Channel 'a' is closed |
| 1933 | Channel 'a' is closed |
| 1934 | ``` |
| 1935 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1936 | <!--- TEST --> |
| 1937 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1938 | There are couple of observations to make out of it. |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1939 | |
| 1940 | First of all, `select` is _biased_ to the first clause. When several clauses are selectable at the same time, |
| 1941 | the first one among them gets selected. Here, both channels are constantly producing strings, so `a` channel, |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1942 | being the first clause in select, wins. However, because we are using unbuffered channel, the `a` gets suspended from |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1943 | time to time on its [send][SendChannel.send] invocation and gives a chance for `b` to send, too. |
| 1944 | |
| 1945 | The second observation, is that [onReceiveOrNull][SelectBuilder.onReceiveOrNull] gets immediately selected when the |
| 1946 | channel is already closed. |
| 1947 | |
| 1948 | ### Selecting to send |
| 1949 | |
| 1950 | Select expression has [onSend][SelectBuilder.onSend] clause that can be used for a great good in combination |
| 1951 | with a biased nature of selection. |
| 1952 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1953 | Let us write an example of producer of integers that sends its values to a `side` channel when |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1954 | the consumers on its primary channel cannot keep up with it: |
| 1955 | |
| 1956 | ```kotlin |
| 1957 | fun produceNumbers(side: SendChannel<Int>) = produce<Int>(CommonPool) { |
| 1958 | for (num in 1..10) { // produce 10 numbers from 1 to 10 |
| 1959 | delay(100) // every 100 ms |
| 1960 | select<Unit> { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 1961 | onSend(num) {} // Send to the primary channel |
| 1962 | side.onSend(num) {} // or to the side channel |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1963 | } |
| 1964 | } |
| 1965 | } |
| 1966 | ``` |
| 1967 | |
| 1968 | Consumer is going to be quite slow, taking 250 ms to process each number: |
| 1969 | |
| 1970 | ```kotlin |
| 1971 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1972 | val side = Channel<Int>() // allocate side channel |
| 1973 | launch(context) { // this is a very fast consumer for the side channel |
| 1974 | for (num in side) println("Side channel has $num") |
| 1975 | } |
| 1976 | for (num in produceNumbers(side)) { |
| 1977 | println("Consuming $num") |
| 1978 | delay(250) // let us digest the consumed number properly, do not hurry |
| 1979 | } |
| 1980 | println("Done consuming") |
| 1981 | } |
| 1982 | ``` |
| 1983 | |
| 1984 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-select-03.kt) |
| 1985 | |
| 1986 | So let us see what happens: |
| 1987 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1988 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 1989 | Consuming 1 |
| 1990 | Side channel has 2 |
| 1991 | Side channel has 3 |
| 1992 | Consuming 4 |
| 1993 | Side channel has 5 |
| 1994 | Side channel has 6 |
| 1995 | Consuming 7 |
| 1996 | Side channel has 8 |
| 1997 | Side channel has 9 |
| 1998 | Consuming 10 |
| 1999 | Done consuming |
| 2000 | ``` |
| 2001 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2002 | <!--- TEST --> |
| 2003 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2004 | ### Selecting deferred values |
| 2005 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2006 | Deferred values can be selected using [onAwait][SelectBuilder.onAwait] clause. |
| 2007 | Let us start with an async function that returns a deferred string value after |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2008 | a random delay: |
| 2009 | |
| 2010 | <!--- INCLUDE .*/example-select-04.kt |
| 2011 | import java.util.* |
| 2012 | --> |
| 2013 | |
| 2014 | ```kotlin |
| 2015 | fun asyncString(time: Int) = async(CommonPool) { |
| 2016 | delay(time.toLong()) |
| 2017 | "Waited for $time ms" |
| 2018 | } |
| 2019 | ``` |
| 2020 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2021 | Let us start a dozen of them with a random delay. |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2022 | |
| 2023 | ```kotlin |
| 2024 | fun asyncStringsList(): List<Deferred<String>> { |
| 2025 | val random = Random(3) |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2026 | return List(12) { asyncString(random.nextInt(1000)) } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2027 | } |
| 2028 | ``` |
| 2029 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2030 | Now the main function awaits for the first of them to complete and counts the number of deferred values |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2031 | that are still active. Note, that we've used here the fact that `select` expression is a Kotlin DSL, |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2032 | so we can provide clauses for it using an arbitrary code. In this case we iterate over a list |
| 2033 | of deferred values to provide `onAwait` clause for each deferred value. |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2034 | |
| 2035 | ```kotlin |
| 2036 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2037 | val list = asyncStringsList() |
| 2038 | val result = select<String> { |
| 2039 | list.withIndex().forEach { (index, deferred) -> |
| 2040 | deferred.onAwait { answer -> |
| 2041 | "Deferred $index produced answer '$answer'" |
| 2042 | } |
| 2043 | } |
| 2044 | } |
| 2045 | println(result) |
Roman Elizarov | 7c864d8 | 2017-02-27 10:17:50 +0300 | [diff] [blame] | 2046 | val countActive = list.count { it.isActive } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2047 | println("$countActive coroutines are still active") |
| 2048 | } |
| 2049 | ``` |
| 2050 | |
| 2051 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-select-04.kt) |
| 2052 | |
| 2053 | The output is: |
| 2054 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2055 | ```text |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2056 | Deferred 4 produced answer 'Waited for 128 ms' |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2057 | 11 coroutines are still active |
| 2058 | ``` |
| 2059 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2060 | <!--- TEST --> |
| 2061 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2062 | ### Switch over a channel of deferred values |
| 2063 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2064 | Let us write a channel producer function that consumes a channel of deferred string values, waits for each received |
| 2065 | deferred value, but only until the next deferred value comes over or the channel is closed. This example puts together |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2066 | [onReceiveOrNull][SelectBuilder.onReceiveOrNull] and [onAwait][SelectBuilder.onAwait] clauses in the same `select`: |
| 2067 | |
| 2068 | ```kotlin |
| 2069 | fun switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String>(CommonPool) { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2070 | var current = input.receive() // start with first received deferred value |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2071 | while (isActive) { // loop while not cancelled/closed |
| 2072 | val next = select<Deferred<String>?> { // return next deferred value from this select or null |
| 2073 | input.onReceiveOrNull { update -> |
| 2074 | update // replaces next value to wait |
| 2075 | } |
| 2076 | current.onAwait { value -> |
| 2077 | send(value) // send value that current deferred has produced |
| 2078 | input.receiveOrNull() // and use the next deferred from the input channel |
| 2079 | } |
| 2080 | } |
| 2081 | if (next == null) { |
| 2082 | println("Channel was closed") |
| 2083 | break // out of loop |
| 2084 | } else { |
| 2085 | current = next |
| 2086 | } |
| 2087 | } |
| 2088 | } |
| 2089 | ``` |
| 2090 | |
| 2091 | To test it, we'll use a simple async function that resolves to a specified string after a specified time: |
| 2092 | |
| 2093 | ```kotlin |
| 2094 | fun asyncString(str: String, time: Long) = async(CommonPool) { |
| 2095 | delay(time) |
| 2096 | str |
| 2097 | } |
| 2098 | ``` |
| 2099 | |
| 2100 | The main function just launches a coroutine to print results of `switchMapDeferreds` and sends some test |
| 2101 | data to it: |
| 2102 | |
| 2103 | ```kotlin |
| 2104 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2105 | val chan = Channel<Deferred<String>>() // the channel for test |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2106 | launch(context) { // launch printing coroutine |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2107 | for (s in switchMapDeferreds(chan)) |
| 2108 | println(s) // print each received string |
| 2109 | } |
| 2110 | chan.send(asyncString("BEGIN", 100)) |
| 2111 | delay(200) // enough time for "BEGIN" to be produced |
| 2112 | chan.send(asyncString("Slow", 500)) |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2113 | delay(100) // not enough time to produce slow |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2114 | chan.send(asyncString("Replace", 100)) |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2115 | delay(500) // give it time before the last one |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2116 | chan.send(asyncString("END", 500)) |
| 2117 | delay(1000) // give it time to process |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2118 | chan.close() // close the channel ... |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2119 | delay(500) // and wait some time to let it finish |
| 2120 | } |
| 2121 | ``` |
| 2122 | |
| 2123 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-select-05.kt) |
| 2124 | |
| 2125 | The result of this code: |
| 2126 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2127 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2128 | BEGIN |
| 2129 | Replace |
| 2130 | END |
| 2131 | Channel was closed |
| 2132 | ``` |
| 2133 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2134 | <!--- TEST --> |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2135 | |
Roman Elizarov | e0c817d | 2017-02-10 10:22:01 +0300 | [diff] [blame] | 2136 | <!--- SITE_ROOT https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core --> |
| 2137 | <!--- DOCS_ROOT kotlinx-coroutines-core/target/dokka/kotlinx-coroutines-core --> |
| 2138 | <!--- INDEX kotlinx.coroutines.experimental --> |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2139 | [launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/launch.html |
| 2140 | [delay]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/delay.html |
| 2141 | [runBlocking]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/run-blocking.html |
| 2142 | [Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/index.html |
| 2143 | [CancellationException]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-cancellation-exception.html |
| 2144 | [yield]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/yield.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2145 | [CoroutineScope.isActive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/is-active.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2146 | [CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/index.html |
| 2147 | [run]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/run.html |
| 2148 | [NonCancellable]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-non-cancellable/index.html |
| 2149 | [withTimeout]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-timeout.html |
| 2150 | [async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/async.html |
| 2151 | [Deferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/index.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2152 | [Deferred.await]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/await.html |
| 2153 | [Job.start]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/start.html |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2154 | [CommonPool]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-common-pool/index.html |
| 2155 | [CoroutineDispatcher]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-dispatcher/index.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2156 | [CoroutineScope.context]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/context.html |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2157 | [Unconfined]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-unconfined/index.html |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2158 | [newCoroutineContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/new-coroutine-context.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2159 | [CoroutineName]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-name/index.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2160 | [Job.invoke]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/invoke.html |
| 2161 | [Job.cancel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/cancel.html |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2162 | <!--- INDEX kotlinx.coroutines.experimental.sync --> |
| 2163 | [Mutex]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/index.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2164 | [Mutex.lock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/lock.html |
| 2165 | [Mutex.unlock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/unlock.html |
Roman Elizarov | e0c817d | 2017-02-10 10:22:01 +0300 | [diff] [blame] | 2166 | <!--- INDEX kotlinx.coroutines.experimental.channels --> |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2167 | [Channel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-channel/index.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2168 | [SendChannel.send]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/send.html |
| 2169 | [ReceiveChannel.receive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-receive-channel/receive.html |
| 2170 | [SendChannel.close]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/close.html |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 2171 | [produce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/produce.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2172 | [Channel.invoke]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-channel/invoke.html |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2173 | [actor]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/actor.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2174 | <!--- INDEX kotlinx.coroutines.experimental.selects --> |
| 2175 | [select]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/select.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2176 | [SelectBuilder.onReceive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/-select-builder/on-receive.html |
| 2177 | [SelectBuilder.onReceiveOrNull]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/-select-builder/on-receive-or-null.html |
| 2178 | [SelectBuilder.onSend]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/-select-builder/on-send.html |
| 2179 | [SelectBuilder.onAwait]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/-select-builder/on-await.html |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2180 | <!--- END --> |