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