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