Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 1 | <!--- |
| 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 | |
| 17 | --> |
| 18 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 19 | # Guide to kotlinx.coroutines by example |
| 20 | |
| 21 | This is a short guide on core features of `kotlinx.coroutines` with a series of examples. |
| 22 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 23 | ## Table of contents |
| 24 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 25 | <!--- TOC --> |
| 26 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 27 | * [Coroutine basics](#coroutine-basics) |
| 28 | * [Your first coroutine](#your-first-coroutine) |
| 29 | * [Bridging blocking and non-blocking worlds](#bridging-blocking-and-non-blocking-worlds) |
| 30 | * [Waiting for a job](#waiting-for-a-job) |
| 31 | * [Extract function refactoring](#extract-function-refactoring) |
| 32 | * [Coroutines ARE light-weight](#coroutines-are-light-weight) |
| 33 | * [Coroutines are like daemon threads](#coroutines-are-like-daemon-threads) |
| 34 | * [Cancellation and timeouts](#cancellation-and-timeouts) |
| 35 | * [Cancelling coroutine execution](#cancelling-coroutine-execution) |
| 36 | * [Cancellation is cooperative](#cancellation-is-cooperative) |
| 37 | * [Making computation code cancellable](#making-computation-code-cancellable) |
| 38 | * [Closing resources with finally](#closing-resources-with-finally) |
| 39 | * [Run non-cancellable block](#run-non-cancellable-block) |
| 40 | * [Timeout](#timeout) |
| 41 | * [Composing suspending functions](#composing-suspending-functions) |
| 42 | * [Sequential by default](#sequential-by-default) |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 43 | * [Concurrent using async](#concurrent-using-async) |
| 44 | * [Lazily started async](#lazily-started-async) |
| 45 | * [Async-style functions](#async-style-functions) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 46 | * [Coroutine context and dispatchers](#coroutine-context-and-dispatchers) |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 47 | * [Dispatchers and threads](#dispatchers-and-threads) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 48 | * [Unconfined vs confined dispatcher](#unconfined-vs-confined-dispatcher) |
| 49 | * [Debugging coroutines and threads](#debugging-coroutines-and-threads) |
| 50 | * [Jumping between threads](#jumping-between-threads) |
| 51 | * [Job in the context](#job-in-the-context) |
| 52 | * [Children of a coroutine](#children-of-a-coroutine) |
| 53 | * [Combining contexts](#combining-contexts) |
| 54 | * [Naming coroutines for debugging](#naming-coroutines-for-debugging) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 55 | * [Channels](#channels) |
| 56 | * [Channel basics](#channel-basics) |
| 57 | * [Closing and iteration over channels](#closing-and-iteration-over-channels) |
| 58 | * [Building channel producers](#building-channel-producers) |
| 59 | * [Pipelines](#pipelines) |
| 60 | * [Prime numbers with pipeline](#prime-numbers-with-pipeline) |
| 61 | * [Fan-out](#fan-out) |
| 62 | * [Fan-in](#fan-in) |
| 63 | * [Buffered channels](#buffered-channels) |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 64 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 65 | <!--- KNIT kotlinx-coroutines-core/src/test/kotlin/guide/.*\.kt --> |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 66 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 67 | <!--- INCLUDE .*/example-([a-z]+)-([0-9]+)\.kt |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 68 | /* |
| 69 | * Copyright 2016-2017 JetBrains s.r.o. |
| 70 | * |
| 71 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 72 | * you may not use this file except in compliance with the License. |
| 73 | * You may obtain a copy of the License at |
| 74 | * |
| 75 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 76 | * |
| 77 | * Unless required by applicable law or agreed to in writing, software |
| 78 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 79 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 80 | * See the License for the specific language governing permissions and |
| 81 | * limitations under the License. |
| 82 | */ |
| 83 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 84 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 85 | package guide.$$1.example$$2 |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 86 | |
| 87 | import kotlinx.coroutines.experimental.* |
| 88 | --> |
| 89 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 90 | ## Coroutine basics |
| 91 | |
| 92 | This section covers basic coroutine concepts. |
| 93 | |
| 94 | ### Your first coroutine |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 95 | |
| 96 | Run the following code: |
| 97 | |
| 98 | ```kotlin |
| 99 | fun main(args: Array<String>) { |
| 100 | launch(CommonPool) { // create new coroutine in common thread pool |
| 101 | delay(1000L) // non-blocking delay for 1 second (default time unit is ms) |
| 102 | println("World!") // print after delay |
| 103 | } |
| 104 | println("Hello,") // main function continues while coroutine is delayed |
| 105 | Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive |
| 106 | } |
| 107 | ``` |
| 108 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 109 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-01.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 110 | |
| 111 | Run this code: |
| 112 | |
| 113 | ``` |
| 114 | Hello, |
| 115 | World! |
| 116 | ``` |
| 117 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 118 | Essentially, coroutines are light-weight threads. |
| 119 | They are launched with [launch] _coroutine builder_. |
| 120 | You can achieve the same result replacing |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 121 | `launch(CommonPool) { ... }` with `thread { ... }` and `delay(...)` with `Thread.sleep(...)`. Try it. |
| 122 | |
| 123 | If you start by replacing `launch(CommonPool)` by `thread`, the compiler produces the following error: |
| 124 | |
| 125 | ``` |
| 126 | Error: Kotlin: Suspend functions are only allowed to be called from a coroutine or another suspend function |
| 127 | ``` |
| 128 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 129 | 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] | 130 | coroutine and it can be only used from a coroutine. |
| 131 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 132 | ### Bridging blocking and non-blocking worlds |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 133 | |
| 134 | The first example mixes _non-blocking_ `delay(...)` and _blocking_ `Thread.sleep(...)` in the same |
| 135 | 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] | 136 | worlds by using [runBlocking]: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 137 | |
| 138 | ```kotlin |
| 139 | fun main(args: Array<String>) = runBlocking<Unit> { // start main coroutine |
| 140 | launch(CommonPool) { // create new coroutine in common thread pool |
| 141 | delay(1000L) |
| 142 | println("World!") |
| 143 | } |
| 144 | println("Hello,") // main coroutine continues while child is delayed |
| 145 | delay(2000L) // non-blocking delay for 2 seconds to keep JVM alive |
| 146 | } |
| 147 | ``` |
| 148 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 149 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-02.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 150 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 151 | 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] | 152 | |
| 153 | `runBlocking { ... }` works as an adaptor that is used here to start the top-level main coroutine. |
| 154 | The regular code outside of `runBlocking` _blocks_, until the coroutine inside `runBlocking` is active. |
| 155 | |
| 156 | This is also a way to write unit-tests for suspending functions: |
| 157 | |
| 158 | ```kotlin |
| 159 | class MyTest { |
| 160 | @Test |
| 161 | fun testMySuspendingFunction() = runBlocking<Unit> { |
| 162 | // here we can use suspending functions using any assertion style that we like |
| 163 | } |
| 164 | } |
| 165 | ``` |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 166 | |
| 167 | <!--- CLEAR --> |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 168 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 169 | ### Waiting for a job |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 170 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 171 | 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] | 172 | 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] | 173 | |
| 174 | ```kotlin |
| 175 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 176 | val job = launch(CommonPool) { // create new coroutine and keep a reference to its Job |
| 177 | delay(1000L) |
| 178 | println("World!") |
| 179 | } |
| 180 | println("Hello,") |
| 181 | job.join() // wait until child coroutine completes |
| 182 | } |
| 183 | ``` |
| 184 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 185 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-03.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 186 | |
| 187 | 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] | 188 | the background job in any way. Much better. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 189 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 190 | ### Extract function refactoring |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 191 | |
| 192 | Let's extract the block of code inside `launch(CommonPool} { ... }` into a separate function. When you |
| 193 | perform "Extract function" refactoring on this code you get a new function with `suspend` modifier. |
| 194 | That is your first _suspending function_. Suspending functions can be used inside coroutines |
| 195 | just like regular functions, but their additional feature is that they can, in turn, |
| 196 | use other suspending functions, like `delay` in this example, to _suspend_ execution of a coroutine. |
| 197 | |
| 198 | ```kotlin |
| 199 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 200 | val job = launch(CommonPool) { doWorld() } |
| 201 | println("Hello,") |
| 202 | job.join() |
| 203 | } |
| 204 | |
| 205 | // this is your first suspending function |
| 206 | suspend fun doWorld() { |
| 207 | delay(1000L) |
| 208 | println("World!") |
| 209 | } |
| 210 | ``` |
| 211 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 212 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-04.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 213 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 214 | ### Coroutines ARE light-weight |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 215 | |
| 216 | Run the following code: |
| 217 | |
| 218 | ```kotlin |
| 219 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 220 | val jobs = List(100_000) { // create a lot of coroutines and list their jobs |
| 221 | launch(CommonPool) { |
| 222 | delay(1000L) |
| 223 | print(".") |
| 224 | } |
| 225 | } |
| 226 | jobs.forEach { it.join() } // wait for all jobs to complete |
| 227 | } |
| 228 | ``` |
| 229 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 230 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-05.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 231 | |
| 232 | It starts 100K coroutines and, after a second, each coroutine prints a dot. |
| 233 | Now, try that with threads. What would happen? (Most likely your code will produce some sort of out-of-memory error) |
| 234 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 235 | ### Coroutines are like daemon threads |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 236 | |
| 237 | 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] | 238 | returns from the main function after some delay: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 239 | |
| 240 | ```kotlin |
| 241 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 242 | launch(CommonPool) { |
| 243 | repeat(1000) { i -> |
| 244 | println("I'm sleeping $i ...") |
| 245 | delay(500L) |
| 246 | } |
| 247 | } |
| 248 | delay(1300L) // just quit after delay |
| 249 | } |
| 250 | ``` |
| 251 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 252 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-06.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 253 | |
| 254 | You can run and see that it prints three lines and terminates: |
| 255 | |
| 256 | ``` |
| 257 | I'm sleeping 0 ... |
| 258 | I'm sleeping 1 ... |
| 259 | I'm sleeping 2 ... |
| 260 | ``` |
| 261 | |
| 262 | Active coroutines do not keep the process alive. They are like daemon threads. |
| 263 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 264 | ## Cancellation and timeouts |
| 265 | |
| 266 | This section covers coroutine cancellation and timeouts. |
| 267 | |
| 268 | ### Cancelling coroutine execution |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 269 | |
| 270 | In small application the return from "main" method might sound like a good idea to get all coroutines |
| 271 | 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] | 272 | 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] | 273 | |
| 274 | ```kotlin |
| 275 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 276 | val job = launch(CommonPool) { |
| 277 | repeat(1000) { i -> |
| 278 | println("I'm sleeping $i ...") |
| 279 | delay(500L) |
| 280 | } |
| 281 | } |
| 282 | delay(1300L) // delay a bit |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 283 | println("main: I'm tired of waiting!") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 284 | job.cancel() // cancels the job |
| 285 | delay(1300L) // delay a bit to ensure it was cancelled indeed |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 286 | println("main: Now I can quit.") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 287 | } |
| 288 | ``` |
| 289 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 290 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-01.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 291 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 292 | It produces the following output: |
| 293 | |
| 294 | ``` |
| 295 | I'm sleeping 0 ... |
| 296 | I'm sleeping 1 ... |
| 297 | I'm sleeping 2 ... |
| 298 | main: I'm tired of waiting! |
| 299 | main: Now I can quit. |
| 300 | ``` |
| 301 | |
| 302 | As soon as main invokes `job.cancel`, we don't see any output from the other coroutine because it was cancelled. |
| 303 | |
| 304 | ### Cancellation is cooperative |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 305 | |
Tair Rzayev | af73462 | 2017-02-01 22:30:16 +0200 | [diff] [blame] | 306 | 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] | 307 | 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] | 308 | 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] | 309 | a computation and does not check for cancellation, then it cannot be cancelled, like the following |
| 310 | example shows: |
| 311 | |
| 312 | ```kotlin |
| 313 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 314 | val job = launch(CommonPool) { |
| 315 | var nextPrintTime = 0L |
| 316 | var i = 0 |
| 317 | while (true) { // computation loop |
| 318 | val currentTime = System.currentTimeMillis() |
| 319 | if (currentTime >= nextPrintTime) { |
| 320 | println("I'm sleeping ${i++} ...") |
| 321 | nextPrintTime = currentTime + 500L |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 | delay(1300L) // delay a bit |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 326 | println("main: I'm tired of waiting!") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 327 | job.cancel() // cancels the job |
| 328 | delay(1300L) // delay a bit to see if it was cancelled.... |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 329 | println("main: Now I can quit.") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 330 | } |
| 331 | ``` |
| 332 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 333 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-02.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 334 | |
| 335 | Run it to see that it continues to print "I'm sleeping" even after cancellation. |
| 336 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 337 | ### Making computation code cancellable |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 338 | |
| 339 | 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] | 340 | 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] | 341 | 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] | 342 | |
| 343 | Replace `while (true)` in the previous example with `while (isActive)` and rerun it. |
| 344 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 345 | ```kotlin |
| 346 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 347 | val job = launch(CommonPool) { |
| 348 | var nextPrintTime = 0L |
| 349 | var i = 0 |
| 350 | while (isActive) { // cancellable computation loop |
| 351 | val currentTime = System.currentTimeMillis() |
| 352 | if (currentTime >= nextPrintTime) { |
| 353 | println("I'm sleeping ${i++} ...") |
| 354 | nextPrintTime = currentTime + 500L |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | delay(1300L) // delay a bit |
| 359 | println("main: I'm tired of waiting!") |
| 360 | job.cancel() // cancels the job |
| 361 | delay(1300L) // delay a bit to see if it was cancelled.... |
| 362 | println("main: Now I can quit.") |
| 363 | } |
| 364 | ``` |
| 365 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 366 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-03.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 367 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 368 | As you can see, now this loop can be cancelled. [isActive][CoroutineScope.isActive] is a property that is available inside |
| 369 | the code of coroutines via [CoroutineScope] object. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 370 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 371 | ### Closing resources with finally |
| 372 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 373 | Cancellable suspending functions throw [CancellationException] on cancellation which can be handled in |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 374 | all the usual way. For example, the `try {...} finally {...}` and Kotlin `use` function execute their |
| 375 | finalization actions normally when coroutine is cancelled: |
| 376 | |
| 377 | ```kotlin |
| 378 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 379 | val job = launch(CommonPool) { |
| 380 | try { |
| 381 | repeat(1000) { i -> |
| 382 | println("I'm sleeping $i ...") |
| 383 | delay(500L) |
| 384 | } |
| 385 | } finally { |
| 386 | println("I'm running finally") |
| 387 | } |
| 388 | } |
| 389 | delay(1300L) // delay a bit |
| 390 | println("main: I'm tired of waiting!") |
| 391 | job.cancel() // cancels the job |
| 392 | delay(1300L) // delay a bit to ensure it was cancelled indeed |
| 393 | println("main: Now I can quit.") |
| 394 | } |
| 395 | ``` |
| 396 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 397 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-04.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 398 | |
| 399 | The example above produces the following output: |
| 400 | |
| 401 | ``` |
| 402 | I'm sleeping 0 ... |
| 403 | I'm sleeping 1 ... |
| 404 | I'm sleeping 2 ... |
| 405 | main: I'm tired of waiting! |
| 406 | I'm running finally |
| 407 | main: Now I can quit. |
| 408 | ``` |
| 409 | |
| 410 | ### Run non-cancellable block |
| 411 | |
| 412 | 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] | 413 | [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] | 414 | problem, since all well-behaving closing operations (closing a file, cancelling a job, or closing any kind of a |
| 415 | communication channel) are usually non-blocking and do not involve any suspending functions. However, in the |
| 416 | 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] | 417 | `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] | 418 | |
| 419 | ```kotlin |
| 420 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 421 | val job = launch(CommonPool) { |
| 422 | try { |
| 423 | repeat(1000) { i -> |
| 424 | println("I'm sleeping $i ...") |
| 425 | delay(500L) |
| 426 | } |
| 427 | } finally { |
| 428 | run(NonCancellable) { |
| 429 | println("I'm running finally") |
| 430 | delay(1000L) |
| 431 | println("And I've just delayed for 1 sec because I'm non-cancellable") |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | delay(1300L) // delay a bit |
| 436 | println("main: I'm tired of waiting!") |
| 437 | job.cancel() // cancels the job |
| 438 | delay(1300L) // delay a bit to ensure it was cancelled indeed |
| 439 | println("main: Now I can quit.") |
| 440 | } |
| 441 | ``` |
| 442 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 443 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-05.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 444 | |
| 445 | ### Timeout |
| 446 | |
| 447 | The most obvious reason to cancel coroutine execution in practice, |
| 448 | is because its execution time has exceeded some timeout. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 449 | While you can manually track the reference to the corresponding [Job] and launch a separate coroutine to cancel |
| 450 | 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] | 451 | Look at the following example: |
| 452 | |
| 453 | ```kotlin |
| 454 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 455 | withTimeout(1300L) { |
| 456 | repeat(1000) { i -> |
| 457 | println("I'm sleeping $i ...") |
| 458 | delay(500L) |
| 459 | } |
| 460 | } |
| 461 | } |
| 462 | ``` |
| 463 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 464 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-06.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 465 | |
| 466 | It produces the following output: |
| 467 | |
| 468 | ``` |
| 469 | I'm sleeping 0 ... |
| 470 | I'm sleeping 1 ... |
| 471 | I'm sleeping 2 ... |
| 472 | Exception in thread "main" java.util.concurrent.CancellationException: Timed out waiting for 1300 MILLISECONDS |
| 473 | ``` |
| 474 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 475 | We have not seen the [CancellationException] stack trace printed on the console before. That is because |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 476 | inside a cancelled coroutine `CancellationException` is a considered a normal reason for coroutine completion. |
| 477 | However, in this example we have used `withTimeout` right inside the `main` function. |
| 478 | |
| 479 | Because cancellation is just an exception, all the resources will be closed in a usual way. |
| 480 | You can wrap the code with timeout in `try {...} catch (e: CancellationException) {...}` block if |
| 481 | you need to do some additional action specifically on timeout. |
| 482 | |
| 483 | ## Composing suspending functions |
| 484 | |
| 485 | This section covers various approaches to composition of suspending functions. |
| 486 | |
| 487 | ### Sequential by default |
| 488 | |
| 489 | 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] | 490 | remote service call or computation. We just pretend they are useful, but actually each one just |
| 491 | delays for a second for the purpose of this example: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 492 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 493 | <!--- INCLUDE .*/example-compose-([0-9]+).kt |
| 494 | import kotlin.system.measureTimeMillis |
| 495 | --> |
| 496 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 497 | ```kotlin |
| 498 | suspend fun doSomethingUsefulOne(): Int { |
| 499 | delay(1000L) // pretend we are doing something useful here |
| 500 | return 13 |
| 501 | } |
| 502 | |
| 503 | suspend fun doSomethingUsefulTwo(): Int { |
| 504 | delay(1000L) // pretend we are doing something useful here, too |
| 505 | return 29 |
| 506 | } |
| 507 | ``` |
| 508 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 509 | <!--- INCLUDE .*/example-compose-([0-9]+).kt --> |
| 510 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 511 | What do we do if need to invoke them _sequentially_ -- first `doSomethingUsefulOne` _and then_ |
| 512 | `doSomethingUsefulTwo` and compute the sum of their results? |
| 513 | In practise we do this if we use the results of the first function to make a decision on whether we need |
| 514 | to invoke the second one or to decide on how to invoke it. |
| 515 | |
| 516 | 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] | 517 | 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] | 518 | time it takes to execute both suspending functions: |
| 519 | |
| 520 | ```kotlin |
| 521 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 522 | val time = measureTimeMillis { |
| 523 | val one = doSomethingUsefulOne() |
| 524 | val two = doSomethingUsefulTwo() |
| 525 | println("The answer is ${one + two}") |
| 526 | } |
| 527 | println("Completed in $time ms") |
| 528 | } |
| 529 | ``` |
| 530 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 531 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-01.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 532 | |
| 533 | It produces something like this: |
| 534 | |
| 535 | ``` |
| 536 | The answer is 42 |
| 537 | Completed in 2017 ms |
| 538 | ``` |
| 539 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 540 | ### Concurrent using async |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 541 | |
| 542 | 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] | 543 | 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] | 544 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 545 | Conceptually, [async] is just like [launch]. It starts a separate coroutine which is a light-weight thread |
| 546 | that works concurrently with all the other coroutines. The difference is that `launch` returns a [Job] and |
| 547 | 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] | 548 | 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] | 549 | but `Deferred` is also a `Job`, so you can cancel it if needed. |
| 550 | |
| 551 | ```kotlin |
| 552 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 553 | val time = measureTimeMillis { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 554 | val one = async(CommonPool) { doSomethingUsefulOne() } |
| 555 | val two = async(CommonPool) { doSomethingUsefulTwo() } |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 556 | println("The answer is ${one.await() + two.await()}") |
| 557 | } |
| 558 | println("Completed in $time ms") |
| 559 | } |
| 560 | ``` |
| 561 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 562 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-02.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 563 | |
| 564 | It produces something like this: |
| 565 | |
| 566 | ``` |
| 567 | The answer is 42 |
| 568 | Completed in 1017 ms |
| 569 | ``` |
| 570 | |
| 571 | This is twice as fast, because we have concurrent execution of two coroutines. |
| 572 | Note, that concurrency with coroutines is always explicit. |
| 573 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 574 | ### Lazily started async |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 575 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 576 | There is a laziness option to [async] with `start = false` parameter. |
| 577 | It starts coroutine only when its result is needed by some |
| 578 | [await][Deferred.await] or if a [start][Job.start] function |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 579 | 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] | 580 | |
| 581 | ```kotlin |
| 582 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 583 | val time = measureTimeMillis { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 584 | val one = async(CommonPool, start = false) { doSomethingUsefulOne() } |
| 585 | val two = async(CommonPool, start = false) { doSomethingUsefulTwo() } |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 586 | println("The answer is ${one.await() + two.await()}") |
| 587 | } |
| 588 | println("Completed in $time ms") |
| 589 | } |
| 590 | ``` |
| 591 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 592 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-03.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 593 | |
| 594 | It produces something like this: |
| 595 | |
| 596 | ``` |
| 597 | The answer is 42 |
| 598 | Completed in 2017 ms |
| 599 | ``` |
| 600 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 601 | So, we are back to sequential execution, because we _first_ start and await for `one`, _and then_ start and await |
| 602 | for `two`. It is not the intended use-case for laziness. It is designed as a replacement for |
| 603 | the standard `lazy` function in cases when computation of the value involves suspending functions. |
| 604 | |
| 605 | ### Async-style functions |
| 606 | |
| 607 | We can define async-style functions that invoke `doSomethingUsefulOne` and `doSomethingUsefulTwo` |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 608 | _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] | 609 | either "async" prefix of "Async" suffix to highlight the fact that they only start asynchronous |
| 610 | computation and one needs to use the resulting deferred value to get the result. |
| 611 | |
| 612 | ```kotlin |
| 613 | // The result type of asyncSomethingUsefulOne is Deferred<Int> |
| 614 | fun asyncSomethingUsefulOne() = async(CommonPool) { |
| 615 | doSomethingUsefulOne() |
| 616 | } |
| 617 | |
| 618 | // The result type of asyncSomethingUsefulTwo is Deferred<Int> |
| 619 | fun asyncSomethingUsefulTwo() = async(CommonPool) { |
| 620 | doSomethingUsefulTwo() |
| 621 | } |
| 622 | ``` |
| 623 | |
| 624 | Note, that these `asyncXXX` function are **not** _suspending_ functions. They can be used from anywhere. |
| 625 | However, their use always implies asynchronous (here meaning _concurrent_) execution of their action |
| 626 | with the invoking code. |
| 627 | |
| 628 | The following example shows their use outside of coroutine: |
| 629 | |
| 630 | ```kotlin |
| 631 | // note, that we don't have `runBlocking` to the right of `main` in this example |
| 632 | fun main(args: Array<String>) { |
| 633 | val time = measureTimeMillis { |
| 634 | // we can initiate async actions outside of a coroutine |
| 635 | val one = asyncSomethingUsefulOne() |
| 636 | val two = asyncSomethingUsefulTwo() |
| 637 | // but waiting for a result must involve either suspending or blocking. |
| 638 | // here we use `runBlocking { ... }` to block the main thread while waiting for the result |
| 639 | runBlocking { |
| 640 | println("The answer is ${one.await() + two.await()}") |
| 641 | } |
| 642 | } |
| 643 | println("Completed in $time ms") |
| 644 | } |
| 645 | ``` |
| 646 | |
| 647 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-04.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 648 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 649 | ## Coroutine context and dispatchers |
| 650 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 651 | We've already seen `launch(CommonPool) {...}`, `async(CommonPool) {...}`, `run(NonCancellable) {...}`, etc. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 652 | In these code snippets [CommonPool] and [NonCancellable] are _coroutine contexts_. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 653 | This section covers other available choices. |
| 654 | |
| 655 | ### Dispatchers and threads |
| 656 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 657 | 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] | 658 | the corresponding coroutine uses for its execution. Coroutine dispatcher can confine coroutine execution |
| 659 | to a specific thread, dispatch it to a thread pool, or let it run unconfined. Try the following example: |
| 660 | |
| 661 | ```kotlin |
| 662 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 663 | val jobs = arrayListOf<Job>() |
| 664 | jobs += launch(Unconfined) { // not confined -- will work with main thread |
| 665 | println(" 'Unconfined': I'm working in thread ${Thread.currentThread().name}") |
| 666 | } |
| 667 | jobs += launch(context) { // context of the parent, runBlocking coroutine |
| 668 | println(" 'context': I'm working in thread ${Thread.currentThread().name}") |
| 669 | } |
| 670 | jobs += launch(CommonPool) { // will get dispatched to ForkJoinPool.commonPool (or equivalent) |
| 671 | println(" 'CommonPool': I'm working in thread ${Thread.currentThread().name}") |
| 672 | } |
| 673 | jobs += launch(newSingleThreadContext("MyOwnThread")) { // will get its own new thread |
| 674 | println(" 'newSTC': I'm working in thread ${Thread.currentThread().name}") |
| 675 | } |
| 676 | jobs.forEach { it.join() } |
| 677 | } |
| 678 | ``` |
| 679 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 680 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-01.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 681 | |
| 682 | It produces the following output (maybe in different order): |
| 683 | |
| 684 | ``` |
| 685 | 'Unconfined': I'm working in thread main |
| 686 | 'CommonPool': I'm working in thread ForkJoinPool.commonPool-worker-1 |
| 687 | 'newSTC': I'm working in thread MyOwnThread |
| 688 | 'context': I'm working in thread main |
| 689 | ``` |
| 690 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 691 | The difference between parent [context][CoroutineScope.context] and [Unconfined] context will be shown later. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 692 | |
| 693 | ### Unconfined vs confined dispatcher |
| 694 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 695 | 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] | 696 | first suspension point. After suspension it resumes in the thread that is fully determined by the |
| 697 | suspending function that was invoked. Unconfined dispatcher is appropriate when coroutine does not |
| 698 | consume CPU time nor updates any shared data (like UI) that is confined to a specific thread. |
| 699 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 700 | On the other side, [context][CoroutineScope.context] property that is available inside the block of any coroutine |
| 701 | via [CoroutineScope] interface, is a reference to a context of this particular coroutine. |
| 702 | 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] | 703 | is confined to be invoker thread, so inheriting it has the effect of confining execution to |
| 704 | this thread with a predictable FIFO scheduling. |
| 705 | |
| 706 | ```kotlin |
| 707 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 708 | val jobs = arrayListOf<Job>() |
| 709 | jobs += launch(Unconfined) { // not confined -- will work with main thread |
| 710 | println(" 'Unconfined': I'm working in thread ${Thread.currentThread().name}") |
| 711 | delay(1000) |
| 712 | println(" 'Unconfined': After delay in thread ${Thread.currentThread().name}") |
| 713 | } |
| 714 | jobs += launch(context) { // context of the parent, runBlocking coroutine |
| 715 | println(" 'context': I'm working in thread ${Thread.currentThread().name}") |
| 716 | delay(1000) |
| 717 | println(" 'context': After delay in thread ${Thread.currentThread().name}") |
| 718 | } |
| 719 | jobs.forEach { it.join() } |
| 720 | } |
| 721 | ``` |
| 722 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 723 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-contest-02.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 724 | |
| 725 | Produces the output: |
| 726 | |
| 727 | ``` |
| 728 | 'Unconfined': I'm working in thread main |
| 729 | 'context': I'm working in thread main |
| 730 | 'Unconfined': After delay in thread kotlinx.coroutines.ScheduledExecutor |
| 731 | 'context': After delay in thread main |
| 732 | ``` |
| 733 | |
| 734 | So, the coroutine the had inherited `context` of `runBlocking {...}` continues to execute in the `main` thread, |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 735 | while the unconfined one had resumed in the scheduler thread that [delay] function is using. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 736 | |
| 737 | ### Debugging coroutines and threads |
| 738 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 739 | Coroutines can suspend on one thread and resume on another thread with [Unconfined] dispatcher or |
| 740 | 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] | 741 | figure out what coroutine was doing what, where, and when. The common approach to debugging applications with |
| 742 | threads is to print the thread name in the log file on each log statement. This feature is universally supported |
| 743 | by logging frameworks. When using coroutines, the thread name alone does not give much of a context, so |
| 744 | `kotlinx.coroutines` includes debugging facilities to make it easier. |
| 745 | |
| 746 | Run the following code with `-Dkotlinx.coroutines.debug` JVM option: |
| 747 | |
| 748 | ```kotlin |
| 749 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 750 | |
| 751 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 752 | val a = async(context) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 753 | log("I'm computing a piece of the answer") |
| 754 | 6 |
| 755 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 756 | val b = async(context) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 757 | log("I'm computing another piece of the answer") |
| 758 | 7 |
| 759 | } |
| 760 | log("The answer is ${a.await() * b.await()}") |
| 761 | } |
| 762 | ``` |
| 763 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 764 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-03.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 765 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 766 | There are three coroutines. The main coroutine (#1) -- `runBlocking` one, |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 767 | and two coroutines computing deferred values `a` (#2) and `b` (#3). |
| 768 | They are all executing in the context of `runBlocking` and are confined to the main thread. |
| 769 | The output of this code is: |
| 770 | |
| 771 | ``` |
| 772 | [main @coroutine#2] I'm computing a piece of the answer |
| 773 | [main @coroutine#3] I'm computing another piece of the answer |
| 774 | [main @coroutine#1] The answer is 42 |
| 775 | ``` |
| 776 | |
| 777 | The `log` function prints the name of the thread in square brackets and you can see, that it is the `main` |
| 778 | thread, but the identifier of the currently executing coroutine is appended to it. This identifier |
| 779 | is consecutively assigned to all created coroutines when debugging mode is turned on. |
| 780 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 781 | 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] | 782 | |
| 783 | ### Jumping between threads |
| 784 | |
| 785 | Run the following code with `-Dkotlinx.coroutines.debug` JVM option: |
| 786 | |
| 787 | ```kotlin |
| 788 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 789 | |
| 790 | fun main(args: Array<String>) { |
| 791 | val ctx1 = newSingleThreadContext("Ctx1") |
| 792 | val ctx2 = newSingleThreadContext("Ctx2") |
| 793 | runBlocking(ctx1) { |
| 794 | log("Started in ctx1") |
| 795 | run(ctx2) { |
| 796 | log("Working in ctx2") |
| 797 | } |
| 798 | log("Back to ctx1") |
| 799 | } |
| 800 | } |
| 801 | ``` |
| 802 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 803 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-04.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 804 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 805 | It demonstrates two new techniques. One is using [runBlocking] with an explicitly specified context, and |
| 806 | 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] | 807 | same coroutine as you can see in the output below: |
| 808 | |
| 809 | ``` |
| 810 | [Ctx1 @coroutine#1] Started in ctx1 |
| 811 | [Ctx2 @coroutine#1] Working in ctx2 |
| 812 | [Ctx1 @coroutine#1] Back to ctx1 |
| 813 | ``` |
| 814 | |
| 815 | ### Job in the context |
| 816 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 817 | The coroutine [Job] is part of its context. The coroutine can retrieve it from its own context |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 818 | using `context[Job]` expression: |
| 819 | |
| 820 | ```kotlin |
| 821 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 822 | println("My job is ${context[Job]}") |
| 823 | } |
| 824 | ``` |
| 825 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 826 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-05.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 827 | |
| 828 | It produces |
| 829 | |
| 830 | ``` |
| 831 | My job is BlockingCoroutine{isActive=true} |
| 832 | ``` |
| 833 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 834 | So, [isActive][CoroutineScope.isActive] in [CoroutineScope] is just a convenient shortcut for `context[Job]!!.isActive`. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 835 | |
| 836 | ### Children of a coroutine |
| 837 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 838 | When [context][CoroutineScope.context] of a coroutine is used to launch another coroutine, |
| 839 | the [Job] of the new coroutine becomes |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 840 | a _child_ of the parent coroutine's job. When the parent coroutine is cancelled, all its children |
| 841 | are recursively cancelled, too. |
| 842 | |
| 843 | ```kotlin |
| 844 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 845 | // start a coroutine to process some kind of incoming request |
| 846 | val request = launch(CommonPool) { |
| 847 | // it spawns two other jobs, one with its separate context |
| 848 | val job1 = launch(CommonPool) { |
| 849 | println("job1: I have my own context and execute independently!") |
| 850 | delay(1000) |
| 851 | println("job1: I am not affected by cancellation of the request") |
| 852 | } |
| 853 | // and the other inherits the parent context |
| 854 | val job2 = launch(context) { |
| 855 | println("job2: I am a child of the request coroutine") |
| 856 | delay(1000) |
| 857 | println("job2: I will not execute this line if my parent request is cancelled") |
| 858 | } |
| 859 | // request completes when both its sub-jobs complete: |
| 860 | job1.join() |
| 861 | job2.join() |
| 862 | } |
| 863 | delay(500) |
| 864 | request.cancel() // cancel processing of the request |
| 865 | delay(1000) // delay a second to see what happens |
| 866 | println("main: Who has survived request cancellation?") |
| 867 | } |
| 868 | ``` |
| 869 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 870 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-06.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 871 | |
| 872 | The output of this code is: |
| 873 | |
| 874 | ``` |
| 875 | job1: I have my own context and execute independently! |
| 876 | job2: I am a child of the request coroutine |
| 877 | job1: I am not affected by cancellation of the request |
| 878 | main: Who has survived request cancellation? |
| 879 | ``` |
| 880 | |
| 881 | ### Combining contexts |
| 882 | |
| 883 | 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] | 884 | 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] | 885 | its dispatcher replaced: |
| 886 | |
| 887 | ```kotlin |
| 888 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 889 | // start a coroutine to process some kind of incoming request |
| 890 | val request = launch(context) { // use the context of `runBlocking` |
| 891 | // spawns CPU-intensive child job in CommonPool !!! |
| 892 | val job = launch(context + CommonPool) { |
| 893 | println("job: I am a child of the request coroutine, but with a different dispatcher") |
| 894 | delay(1000) |
| 895 | println("job: I will not execute this line if my parent request is cancelled") |
| 896 | } |
| 897 | job.join() // request completes when its sub-job completes |
| 898 | } |
| 899 | delay(500) |
| 900 | request.cancel() // cancel processing of the request |
| 901 | delay(1000) // delay a second to see what happens |
| 902 | println("main: Who has survived request cancellation?") |
| 903 | } |
| 904 | ``` |
| 905 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 906 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-07.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 907 | |
| 908 | The expected outcome of this code is: |
| 909 | |
| 910 | ``` |
| 911 | job: I am a child of the request coroutine, but with a different dispatcher |
| 912 | main: Who has survived request cancellation? |
| 913 | ``` |
| 914 | |
| 915 | ### Naming coroutines for debugging |
| 916 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 917 | 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] | 918 | coming from the same coroutine. However, when coroutine is tied to the processing of a specific request |
| 919 | 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] | 920 | [CoroutineName] serves the same function as a thread name. It'll get displayed in the thread name that |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 921 | is executing this coroutine when debugging more is turned on. |
| 922 | |
| 923 | The following example demonstrates this concept: |
| 924 | |
| 925 | ```kotlin |
| 926 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 927 | |
| 928 | fun main(args: Array<String>) = runBlocking(CoroutineName("main")) { |
| 929 | log("Started main coroutine") |
| 930 | // run two background value computations |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 931 | val v1 = async(CommonPool + CoroutineName("v1coroutine")) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 932 | log("Computing v1") |
| 933 | delay(500) |
| 934 | 252 |
| 935 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 936 | val v2 = async(CommonPool + CoroutineName("v2coroutine")) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 937 | log("Computing v2") |
| 938 | delay(1000) |
| 939 | 6 |
| 940 | } |
| 941 | log("The answer for v1 / v2 = ${v1.await() / v2.await()}") |
| 942 | } |
| 943 | ``` |
| 944 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 945 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-08.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 946 | |
| 947 | The output it produces with `-Dkotlinx.coroutines.debug` JVM option is similar to: |
| 948 | |
| 949 | ``` |
| 950 | [main @main#1] Started main coroutine |
| 951 | [ForkJoinPool.commonPool-worker-1 @v1coroutine#2] Computing v1 |
| 952 | [ForkJoinPool.commonPool-worker-2 @v2coroutine#3] Computing v2 |
| 953 | [main @main#1] The answer for v1 / v2 = 42 |
| 954 | ``` |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 955 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 956 | ## Channels |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 957 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 958 | Deferred values provide a convenient way to transfer a single value between coroutines. |
| 959 | Channels provide a way to transfer a stream of values. |
| 960 | |
| 961 | <!--- INCLUDE .*/example-channel-([0-9]+).kt |
| 962 | import kotlinx.coroutines.experimental.channels.* |
| 963 | --> |
| 964 | |
| 965 | ### Channel basics |
| 966 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 967 | A [Channel] is conceptually very similar to `BlockingQueue`. One key difference is that |
| 968 | instead of a blocking `put` operation it has a suspending [send][SendChannel.send], and instead of |
| 969 | a blocking `take` operation it has a suspending [receive][ReceiveChannel.receive]. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 970 | |
| 971 | ```kotlin |
| 972 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 973 | val channel = Channel<Int>() |
| 974 | launch(CommonPool) { |
| 975 | // this might be heavy CPU-consuming computation or async logic, we'll just send five squares |
| 976 | for (x in 1..5) channel.send(x * x) |
| 977 | } |
| 978 | // here we print five received integers: |
| 979 | repeat(5) { println(channel.receive()) } |
| 980 | println("Done!") |
| 981 | } |
| 982 | ``` |
| 983 | |
| 984 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-01.kt) |
| 985 | |
| 986 | ### Closing and iteration over channels |
| 987 | |
| 988 | Unlike a queue, a channel can be closed to indicate that no more elements are coming. |
| 989 | On the receiver side it is convenient to use a regular `for` loop to receive elements |
| 990 | from the channel. |
| 991 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 992 | 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] | 993 | The iteration stops as soon as this close token is received, so there is a guarantee |
| 994 | that all previously sent elements before the close are received: |
| 995 | |
| 996 | ```kotlin |
| 997 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 998 | val channel = Channel<Int>() |
| 999 | launch(CommonPool) { |
| 1000 | for (x in 1..5) channel.send(x * x) |
| 1001 | channel.close() // we're done sending |
| 1002 | } |
| 1003 | // here we print received values using `for` loop (until the channel is closed) |
| 1004 | for (y in channel) println(y) |
| 1005 | println("Done!") |
| 1006 | } |
| 1007 | ``` |
| 1008 | |
| 1009 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-02.kt) |
| 1010 | |
| 1011 | ### Building channel producers |
| 1012 | |
| 1013 | The pattern where a coroutine is producing a sequence of elements into a channel is quite common. |
| 1014 | You could abstract such a producer into a function that takes channel as its parameter, but this goes contrary |
| 1015 | to common sense that results must be returned from functions. Here is a convenience |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1016 | coroutine builder named [buildChannel] that makes it easy to do it right: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1017 | |
| 1018 | ```kotlin |
| 1019 | fun produceSquares() = buildChannel<Int>(CommonPool) { |
| 1020 | for (x in 1..5) send(x * x) |
| 1021 | } |
| 1022 | |
| 1023 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1024 | val squares = produceSquares() |
| 1025 | for (y in squares) println(y) |
| 1026 | println("Done!") |
| 1027 | } |
| 1028 | ``` |
| 1029 | |
| 1030 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-03.kt) |
| 1031 | |
| 1032 | ### Pipelines |
| 1033 | |
| 1034 | Pipeline is a pattern where one coroutine is producing, possibly infinite, stream of values: |
| 1035 | |
| 1036 | ```kotlin |
| 1037 | fun produceNumbers() = buildChannel<Int>(CommonPool) { |
| 1038 | var x = 1 |
| 1039 | while (true) send(x++) // infinite stream of integers starting from 1 |
| 1040 | } |
| 1041 | ``` |
| 1042 | |
| 1043 | And another coroutine or coroutines are receiving that stream, doing some processing, and sending the result. |
| 1044 | In the below example the numbers are just squared: |
| 1045 | |
| 1046 | ```kotlin |
| 1047 | fun square(numbers: ReceiveChannel<Int>) = buildChannel<Int>(CommonPool) { |
| 1048 | for (x in numbers) send(x * x) |
| 1049 | } |
| 1050 | ``` |
| 1051 | |
| 1052 | The main code starts and connects pipeline: |
| 1053 | |
| 1054 | ```kotlin |
| 1055 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1056 | val numbers = produceNumbers() // produces integers from 1 and on |
| 1057 | val squares = square(numbers) // squares integers |
| 1058 | for (i in 1..5) println(squares.receive()) // print first five |
| 1059 | println("Done!") // we are done |
| 1060 | squares.cancel() // need to cancel these coroutines in a larger app |
| 1061 | numbers.cancel() |
| 1062 | } |
| 1063 | ``` |
| 1064 | |
| 1065 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-04.kt) |
| 1066 | |
| 1067 | We don't have to cancel these coroutines in this example app, because |
| 1068 | [coroutines are like daemon threads](#coroutines-are-like-daemon-threads), |
| 1069 | but in a larger app we'll need to stop our pipeline if we don't need it anymore. |
| 1070 | Alternatively, we could have run pipeline coroutines as |
| 1071 | [children of a coroutine](#children-of-a-coroutine). |
| 1072 | |
| 1073 | ### Prime numbers with pipeline |
| 1074 | |
Cedric Beust | fa0b28f | 2017-02-07 07:07:25 -0800 | [diff] [blame] | 1075 | 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] | 1076 | of coroutines. We start with an infinite sequence of numbers. This time we introduce an |
| 1077 | explicit context parameter, so that caller can control where our coroutines run: |
| 1078 | |
| 1079 | <!--- INCLUDE kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-05.kt |
| 1080 | import kotlin.coroutines.experimental.CoroutineContext |
| 1081 | --> |
| 1082 | |
| 1083 | ```kotlin |
| 1084 | fun numbersFrom(context: CoroutineContext, start: Int) = buildChannel<Int>(context) { |
| 1085 | var x = start |
| 1086 | while (true) send(x++) // infinite stream of integers from start |
| 1087 | } |
| 1088 | ``` |
| 1089 | |
| 1090 | The following pipeline stage filters an incoming stream of numbers, removing all the numbers |
| 1091 | that are divisible by the given prime number: |
| 1092 | |
| 1093 | ```kotlin |
| 1094 | fun filter(context: CoroutineContext, numbers: ReceiveChannel<Int>, prime: Int) = buildChannel<Int>(context) { |
| 1095 | for (x in numbers) if (x % prime != 0) send(x) |
| 1096 | } |
| 1097 | ``` |
| 1098 | |
| 1099 | 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^] | 1100 | and launching new pipeline stage for each prime number found: |
| 1101 | |
| 1102 | ``` |
| 1103 | numbers -> filter(2) -> filter(3) -> filter(5) -> filter(7) ... |
| 1104 | ``` |
| 1105 | |
| 1106 | The following example prints the first ten prime numbers, |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1107 | running the whole pipeline in the context of the main thread: |
| 1108 | |
| 1109 | ```kotlin |
| 1110 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1111 | var cur = numbersFrom(context, 2) |
| 1112 | for (i in 1..10) { |
| 1113 | val prime = cur.receive() |
| 1114 | println(prime) |
| 1115 | cur = filter(context, cur, prime) |
| 1116 | } |
| 1117 | } |
| 1118 | ``` |
| 1119 | |
| 1120 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-05.kt) |
| 1121 | |
| 1122 | The output of this code is: |
| 1123 | |
| 1124 | ``` |
| 1125 | 2 |
| 1126 | 3 |
| 1127 | 5 |
| 1128 | 7 |
| 1129 | 11 |
| 1130 | 13 |
| 1131 | 17 |
| 1132 | 19 |
| 1133 | 23 |
| 1134 | 29 |
| 1135 | ``` |
| 1136 | |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame^] | 1137 | Note, that you can build the same pipeline using `buildIterator` from the standard library. |
| 1138 | Replace `buildSequence` with `buildIterator`, `send` with `yield`, `receive` with `next`, |
| 1139 | `ReceiveChannel` with `Iterator`, and get rid of the context. You will not need `runBlocking` either. |
| 1140 | However, the benefit of a pipeline that uses channels as shown above is that it can actually use |
| 1141 | multiple CPU cores if you run it in [CommonPool] context. |
| 1142 | |
| 1143 | Anyway, this is an extremely impractical way to find prime numbers. In practise, pipelines do involve some |
| 1144 | other suspending invocations (like asynchronous calls to remote services) and these pipelines cannot be |
| 1145 | built using `buildSeqeunce`/`buildIterator`, because they do not allow arbitrary suspension, unlike |
| 1146 | `buildChannel` which is fully asynchronous. |
| 1147 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1148 | ### Fan-out |
| 1149 | |
| 1150 | Multiple coroutines may receive from the same channel, distributing work between themselves. |
| 1151 | Let us start with a producer coroutine that is periodically producing integers |
| 1152 | (ten numbers per second): |
| 1153 | |
| 1154 | ```kotlin |
| 1155 | fun produceNumbers() = buildChannel<Int>(CommonPool) { |
| 1156 | var x = 1 // start from 1 |
| 1157 | while (true) { |
| 1158 | send(x++) // produce next |
| 1159 | delay(100) // wait 0.1s |
| 1160 | } |
| 1161 | } |
| 1162 | ``` |
| 1163 | |
| 1164 | Then we can have several processor coroutines. In this example, they just print their id and |
| 1165 | received number: |
| 1166 | |
| 1167 | ```kotlin |
| 1168 | fun launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch(CommonPool) { |
| 1169 | while (true) { |
| 1170 | val x = channel.receive() |
| 1171 | println("Processor #$id received $x") |
| 1172 | } |
| 1173 | } |
| 1174 | ``` |
| 1175 | |
| 1176 | Now let us launch five processors and let them work for a second. See what happens: |
| 1177 | |
| 1178 | ```kotlin |
| 1179 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1180 | val producer = produceNumbers() |
| 1181 | repeat(5) { launchProcessor(it, producer) } |
| 1182 | delay(1000) |
| 1183 | producer.cancel() // cancel producer coroutine and thus kill them all |
| 1184 | } |
| 1185 | ``` |
| 1186 | |
| 1187 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-06.kt) |
| 1188 | |
| 1189 | The output will be similar to the the following one, albeit the processor ids that receive |
| 1190 | each specific integer may be different: |
| 1191 | |
| 1192 | ``` |
| 1193 | Processor #2 received 1 |
| 1194 | Processor #4 received 2 |
| 1195 | Processor #0 received 3 |
| 1196 | Processor #1 received 4 |
| 1197 | Processor #3 received 5 |
| 1198 | Processor #2 received 6 |
| 1199 | Processor #4 received 7 |
| 1200 | Processor #0 received 8 |
| 1201 | Processor #1 received 9 |
| 1202 | Processor #3 received 10 |
| 1203 | ``` |
| 1204 | |
| 1205 | Note, that cancelling a producer coroutine closes its channel, thus eventually terminating iteration |
| 1206 | over the channel that processor coroutines are doing. |
| 1207 | |
| 1208 | ### Fan-in |
| 1209 | |
| 1210 | Multiple coroutines may send to the same channel. |
| 1211 | For example, let us have a channel of strings, and a suspending function that |
| 1212 | repeatedly sends a specified string to this channel with a specified delay: |
| 1213 | |
| 1214 | ```kotlin |
| 1215 | suspend fun sendString(channel: SendChannel<String>, s: String, time: Long) { |
| 1216 | while (true) { |
| 1217 | delay(time) |
| 1218 | channel.send(s) |
| 1219 | } |
| 1220 | } |
| 1221 | ``` |
| 1222 | |
Cedric Beust | fa0b28f | 2017-02-07 07:07:25 -0800 | [diff] [blame] | 1223 | 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] | 1224 | (in this example we launch them in the context of the main thread): |
| 1225 | |
| 1226 | ```kotlin |
| 1227 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1228 | val channel = Channel<String>() |
| 1229 | launch(context) { sendString(channel, "foo", 200L) } |
| 1230 | launch(context) { sendString(channel, "BAR!", 500L) } |
| 1231 | repeat(6) { // receive first six |
| 1232 | println(channel.receive()) |
| 1233 | } |
| 1234 | } |
| 1235 | ``` |
| 1236 | |
| 1237 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-07.kt) |
| 1238 | |
| 1239 | The output is: |
| 1240 | |
| 1241 | ``` |
| 1242 | foo |
| 1243 | foo |
| 1244 | BAR! |
| 1245 | foo |
| 1246 | foo |
| 1247 | BAR! |
| 1248 | ``` |
| 1249 | |
| 1250 | ### Buffered channels |
| 1251 | |
| 1252 | The channels shown so far had no buffer. Unbuffered channels transfer elements when sender and receiver |
| 1253 | meet each other (aka rendezvous). If send is invoked first, then it is suspended until receive is invoked, |
| 1254 | if receive is invoked first, it is suspended until send is invoked. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1255 | |
| 1256 | Both [Channel()][Channel.invoke] factory function and [buildChannel] builder take an optional `capacity` parameter to |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1257 | specify _buffer size_. Buffer allows senders to send multiple elements before suspending, |
| 1258 | similar to the `BlockingQueue` with a specified capacity, which blocks when buffer is full. |
| 1259 | |
| 1260 | Take a look at the behavior of the following code: |
| 1261 | |
| 1262 | ```kotlin |
| 1263 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1264 | val channel = Channel<Int>(4) // create buffered channel |
| 1265 | launch(context) { // launch sender coroutine |
| 1266 | repeat(10) { |
| 1267 | println("Sending $it") // print before sending each element |
| 1268 | channel.send(it) // will suspend when buffer is full |
| 1269 | } |
| 1270 | } |
| 1271 | // don't receive anything... just wait.... |
| 1272 | delay(1000) |
| 1273 | } |
| 1274 | ``` |
| 1275 | |
| 1276 | > You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-08.kt) |
| 1277 | |
| 1278 | It prints "sending" _five_ times using a buffered channel with capacity of _four_: |
| 1279 | |
| 1280 | ``` |
| 1281 | Sending 0 |
| 1282 | Sending 1 |
| 1283 | Sending 2 |
| 1284 | Sending 3 |
| 1285 | Sending 4 |
| 1286 | ``` |
| 1287 | |
| 1288 | 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] | 1289 | |
| 1290 | <!--- SITE_ROOT https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/ --> |
| 1291 | <!--- INDEX kotlinx-coroutines-core/target/dokka/kotlinx-coroutines-core/kotlinx.coroutines.experimental/index.md --> |
| 1292 | [CommonPool]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-common-pool/index.html |
| 1293 | [CoroutineDispatcher]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-dispatcher/index.html |
| 1294 | [CoroutineName]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-name/index.html |
| 1295 | [CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/index.html |
| 1296 | [CoroutineScope.context]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/context.html |
| 1297 | [CoroutineScope.isActive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/is-active.html |
| 1298 | [Deferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/index.html |
| 1299 | [Deferred.await]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/await.html |
| 1300 | [Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/index.html |
| 1301 | [Job.start]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/start.html |
| 1302 | [NonCancellable]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-non-cancellable/index.html |
| 1303 | [Unconfined]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-unconfined/index.html |
| 1304 | [CancellationException]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-cancellation-exception.html |
| 1305 | [async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/async.html |
| 1306 | [delay]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/delay.html |
| 1307 | [launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/launch.html |
| 1308 | [newCoroutineContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/new-coroutine-context.html |
| 1309 | [run]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/run.html |
| 1310 | [runBlocking]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/run-blocking.html |
| 1311 | [withTimeout]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-timeout.html |
| 1312 | [yield]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/yield.html |
| 1313 | <!--- SITE_ROOT https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/ --> |
| 1314 | <!--- INDEX kotlinx-coroutines-core/target/dokka/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/index.md --> |
| 1315 | [Channel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-channel/index.html |
| 1316 | [Channel.invoke]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/invoke.html |
| 1317 | [ReceiveChannel.receive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/receive.html |
| 1318 | [SendChannel.close]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/close.html |
| 1319 | [SendChannel.send]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/send.html |
| 1320 | [buildChannel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/build-channel.html |
| 1321 | <!--- END --> |