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 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame] | 3 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 4 | */ |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 5 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 6 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | a9687a3 | 2018-06-29 17:28:38 +0300 | [diff] [blame] | 7 | package kotlinx.coroutines.experimental.guide.$$1$$2 |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 8 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 9 | import kotlinx.coroutines.experimental.* |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 10 | --> |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 11 | <!--- KNIT core/kotlinx-coroutines-core/test/guide/.*\.kt --> |
| 12 | <!--- TEST_OUT core/kotlinx-coroutines-core/test/guide/test/GuideTest.kt |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 13 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | a9687a3 | 2018-06-29 17:28:38 +0300 | [diff] [blame] | 14 | package kotlinx.coroutines.experimental.guide.test |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 15 | |
| 16 | import org.junit.Test |
| 17 | |
| 18 | class GuideTest { |
| 19 | --> |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 20 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 21 | # Guide to kotlinx.coroutines by example |
| 22 | |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 23 | This is a guide on core features of `kotlinx.coroutines` with a series of examples. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 24 | |
Roman Elizarov | 2a63892 | 2017-03-04 10:22:43 +0300 | [diff] [blame] | 25 | ## Introduction and setup |
| 26 | |
| 27 | Kotlin, as a language, provides only minimal low-level APIs in its standard library to enable various other |
| 28 | libraries to utilize coroutines. Unlike many other languages with similar capabilities, `async` and `await` |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 29 | are not keywords in Kotlin and are not even part of its standard library. Moreover, Kotlin's concept |
| 30 | of _suspending function_ provides a safer and less error-prone abstraction for for asynchronous |
| 31 | operations than futures and promises. |
Roman Elizarov | 2a63892 | 2017-03-04 10:22:43 +0300 | [diff] [blame] | 32 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 33 | `kotlinx.coroutines` is a rich library for coroutines developed by JetBrains. It contains a number of high-level |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 34 | coroutine-enabled primitives that this guide covers, including `launch`, `async` and others. |
Roman Elizarov | 2a63892 | 2017-03-04 10:22:43 +0300 | [diff] [blame] | 35 | You need to add a dependency on `kotlinx-coroutines-core` module as explained |
| 36 | [here](README.md#using-in-your-projects) to use primitives from this guide in your projects. |
| 37 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 38 | ## Table of contents |
| 39 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 40 | <!--- TOC --> |
| 41 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 42 | * [Coroutine basics](#coroutine-basics) |
| 43 | * [Your first coroutine](#your-first-coroutine) |
| 44 | * [Bridging blocking and non-blocking worlds](#bridging-blocking-and-non-blocking-worlds) |
| 45 | * [Waiting for a job](#waiting-for-a-job) |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 46 | * [Structured concurrency](#structured-concurrency) |
| 47 | * [Scope builder](#scope-builder) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 48 | * [Extract function refactoring](#extract-function-refactoring) |
| 49 | * [Coroutines ARE light-weight](#coroutines-are-light-weight) |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 50 | * [Global coroutines are like daemon threads](#global-coroutines-are-like-daemon-threads) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 51 | * [Cancellation and timeouts](#cancellation-and-timeouts) |
| 52 | * [Cancelling coroutine execution](#cancelling-coroutine-execution) |
| 53 | * [Cancellation is cooperative](#cancellation-is-cooperative) |
| 54 | * [Making computation code cancellable](#making-computation-code-cancellable) |
| 55 | * [Closing resources with finally](#closing-resources-with-finally) |
| 56 | * [Run non-cancellable block](#run-non-cancellable-block) |
| 57 | * [Timeout](#timeout) |
| 58 | * [Composing suspending functions](#composing-suspending-functions) |
| 59 | * [Sequential by default](#sequential-by-default) |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 60 | * [Concurrent using async](#concurrent-using-async) |
| 61 | * [Lazily started async](#lazily-started-async) |
| 62 | * [Async-style functions](#async-style-functions) |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 63 | * [Structured concurrency with async](#structured-concurrency-with-async) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 64 | * [Coroutine context and dispatchers](#coroutine-context-and-dispatchers) |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 65 | * [Dispatchers and threads](#dispatchers-and-threads) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 66 | * [Unconfined vs confined dispatcher](#unconfined-vs-confined-dispatcher) |
| 67 | * [Debugging coroutines and threads](#debugging-coroutines-and-threads) |
| 68 | * [Jumping between threads](#jumping-between-threads) |
| 69 | * [Job in the context](#job-in-the-context) |
| 70 | * [Children of a coroutine](#children-of-a-coroutine) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 71 | * [Parental responsibilities](#parental-responsibilities) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 72 | * [Naming coroutines for debugging](#naming-coroutines-for-debugging) |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 73 | * [Combining context elements](#combining-context-elements) |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 74 | * [Cancellation via explicit job](#cancellation-via-explicit-job) |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame] | 75 | * [Thread-local data](#thread-local-data) |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 76 | * [Exception handling](#exception-handling) |
| 77 | * [Exception propagation](#exception-propagation) |
| 78 | * [CoroutineExceptionHandler](#coroutineexceptionhandler) |
| 79 | * [Cancellation and exceptions](#cancellation-and-exceptions) |
| 80 | * [Exceptions aggregation](#exceptions-aggregation) |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 81 | * [Channels (experimental)](#channels-(experimental)) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 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 | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 91 | * [Ticker channels](#ticker-channels) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 92 | * [Shared mutable state and concurrency](#shared-mutable-state-and-concurrency) |
| 93 | * [The problem](#the-problem) |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 94 | * [Volatiles are of no help](#volatiles-are-of-no-help) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 95 | * [Thread-safe data structures](#thread-safe-data-structures) |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 96 | * [Thread confinement fine-grained](#thread-confinement-fine-grained) |
| 97 | * [Thread confinement coarse-grained](#thread-confinement-coarse-grained) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 98 | * [Mutual exclusion](#mutual-exclusion) |
| 99 | * [Actors](#actors) |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 100 | * [Select expression (experimental)](#select-expression-(experimental)) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 101 | * [Selecting from channels](#selecting-from-channels) |
| 102 | * [Selecting on close](#selecting-on-close) |
| 103 | * [Selecting to send](#selecting-to-send) |
| 104 | * [Selecting deferred values](#selecting-deferred-values) |
| 105 | * [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] | 106 | * [Further reading](#further-reading) |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 107 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 108 | <!--- END_TOC --> |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 109 | |
| 110 | ## Coroutine basics |
| 111 | |
| 112 | This section covers basic coroutine concepts. |
| 113 | |
| 114 | ### Your first coroutine |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 115 | |
| 116 | Run the following code: |
| 117 | |
| 118 | ```kotlin |
| 119 | fun main(args: Array<String>) { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 120 | GlobalScope.launch { // launch new coroutine in background and continue |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 121 | delay(1000L) // non-blocking delay for 1 second (default time unit is ms) |
| 122 | println("World!") // print after delay |
| 123 | } |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 124 | println("Hello,") // main thread continues while coroutine is delayed |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 125 | Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive |
| 126 | } |
| 127 | ``` |
| 128 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 129 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-01.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 130 | |
| 131 | Run this code: |
| 132 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 133 | ```text |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 134 | Hello, |
| 135 | World! |
| 136 | ``` |
| 137 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 138 | <!--- TEST --> |
| 139 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 140 | Essentially, coroutines are light-weight threads. |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 141 | They are launched with [launch] _coroutine builder_ in a context of some [CoroutineScope]. |
| 142 | Here we are launching a new coroutine in the [GlobalScope], meaning that the lifetime of the new |
| 143 | coroutine is limited only by the lifetime of the whole application. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 144 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 145 | You can achieve the same result replacing |
| 146 | `GlobalScope.launch { ... }` with `thread { ... }` and `delay(...)` with `Thread.sleep(...)`. Try it. |
| 147 | |
| 148 | If you start by replacing `GlobalScope.launch` by `thread`, the compiler produces the following error: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 149 | |
| 150 | ``` |
| 151 | Error: Kotlin: Suspend functions are only allowed to be called from a coroutine or another suspend function |
| 152 | ``` |
| 153 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 154 | 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] | 155 | coroutine and it can be only used from a coroutine. |
| 156 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 157 | ### Bridging blocking and non-blocking worlds |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 158 | |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 159 | The first example mixes _non-blocking_ `delay(...)` and _blocking_ `Thread.sleep(...)` in the same code. |
| 160 | It is easy to get lost which one is blocking and which one is not. |
| 161 | Let's be explicit about blocking using [runBlocking] coroutine builder: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 162 | |
| 163 | ```kotlin |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 164 | fun main(args: Array<String>) { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 165 | GlobalScope.launch { // launch new coroutine in background and continue |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 166 | delay(1000L) |
| 167 | println("World!") |
| 168 | } |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 169 | println("Hello,") // main thread continues here immediately |
| 170 | runBlocking { // but this expression blocks the main thread |
| 171 | delay(2000L) // ... while we delay for 2 seconds to keep JVM alive |
| 172 | } |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 173 | } |
| 174 | ``` |
| 175 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 176 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-02.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 177 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 178 | <!--- TEST |
| 179 | Hello, |
| 180 | World! |
| 181 | --> |
| 182 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 183 | The result is the same, but this code uses only non-blocking [delay]. |
Tylos | 81451de | 2017-12-17 21:33:17 +0100 | [diff] [blame] | 184 | The main thread, that invokes `runBlocking`, _blocks_ until the coroutine inside `runBlocking` completes. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 185 | |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 186 | This example can be also rewritten in a more idiomatic way, using `runBlocking` to wrap |
| 187 | the execution of the main function: |
| 188 | |
| 189 | ```kotlin |
| 190 | fun main(args: Array<String>) = runBlocking<Unit> { // start main coroutine |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 191 | GlobalScope.launch { // launch new coroutine in background and continue |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 192 | delay(1000L) |
| 193 | println("World!") |
| 194 | } |
| 195 | println("Hello,") // main coroutine continues here immediately |
| 196 | delay(2000L) // delaying for 2 seconds to keep JVM alive |
| 197 | } |
| 198 | ``` |
| 199 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 200 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-02b.kt) |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 201 | |
| 202 | <!--- TEST |
| 203 | Hello, |
| 204 | World! |
| 205 | --> |
| 206 | |
| 207 | Here `runBlocking<Unit> { ... }` works as an adaptor that is used to start the top-level main coroutine. |
| 208 | We explicitly specify its `Unit` return type, because a well-formed `main` function in Kotlin has to return `Unit`. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 209 | |
| 210 | This is also a way to write unit-tests for suspending functions: |
| 211 | |
| 212 | ```kotlin |
| 213 | class MyTest { |
| 214 | @Test |
| 215 | fun testMySuspendingFunction() = runBlocking<Unit> { |
| 216 | // here we can use suspending functions using any assertion style that we like |
| 217 | } |
| 218 | } |
| 219 | ``` |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 220 | |
| 221 | <!--- CLEAR --> |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 222 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 223 | ### Waiting for a job |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 224 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 225 | 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] | 226 | 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] | 227 | |
| 228 | ```kotlin |
| 229 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 230 | val job = GlobalScope.launch { // launch new coroutine and keep a reference to its Job |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 231 | delay(1000L) |
| 232 | println("World!") |
| 233 | } |
| 234 | println("Hello,") |
| 235 | job.join() // wait until child coroutine completes |
| 236 | } |
| 237 | ``` |
| 238 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 239 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-03.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 240 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 241 | <!--- TEST |
| 242 | Hello, |
| 243 | World! |
| 244 | --> |
| 245 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 246 | 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] | 247 | the background job in any way. Much better. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 248 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 249 | ### Structured concurrency |
| 250 | |
| 251 | There is still something to be desired for practical usage of coroutines. |
| 252 | When we use `GlobalScope.launch` we create a top-level coroutine. Even though it is light-weight, it still |
| 253 | consumes some memory resources while it runs. If we forget to keep a reference to the newly launched |
| 254 | coroutine it still runs. What if the code in the coroutine hangs (for example, we erroneously |
| 255 | delay for too long), what if we launched too many coroutines and ran out of memory? |
| 256 | Having to manually keep a reference to all the launched coroutines and [join][Job.join] them is error-prone. |
| 257 | |
| 258 | There is a better solution. We can use structured concurrency in our code. |
| 259 | Instead of launching coroutines in the [GlobalScope], just like we usually do with threads (threads are always global), |
| 260 | we can launch coroutines in the specific scope of the operation we are performing. |
| 261 | |
| 262 | In our example, we have `main` function that is turned into a coroutine using [runBlocking] coroutine builder. |
| 263 | Every coroutine builder, including `runBlocking`, adds an instance of [CoroutineScope] to the scope its code block. |
| 264 | We can launch coroutines in this scope without having to `join` them explicitly, because |
| 265 | an outer coroutine (`runBlocking` in our example) does not complete until all the coroutines launched |
| 266 | in its scope complete. Thus, we can make our example simpler: |
| 267 | |
| 268 | ```kotlin |
| 269 | fun main(args: Array<String>) = runBlocking<Unit> { // this: CoroutineScope |
| 270 | launch { // launch new coroutine in the scope of runBlocking |
| 271 | delay(1000L) |
| 272 | println("World!") |
| 273 | } |
| 274 | println("Hello,") |
| 275 | } |
| 276 | ``` |
| 277 | |
| 278 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-03s.kt) |
| 279 | |
| 280 | <!--- TEST |
| 281 | Hello, |
| 282 | World! |
| 283 | --> |
| 284 | |
| 285 | ### Scope builder |
| 286 | In addition to the coroutine scope provided by different builders, it is possible to declare your own scope using |
| 287 | [coroutineScope] builder. It creates new coroutine scope and does not complete until all launched children |
| 288 | complete. The main difference between [runBlocking] and [coroutineScope] is that the latter does not block the current thread |
| 289 | while waiting for all children to complete. |
| 290 | |
| 291 | ```kotlin |
| 292 | fun main(args: Array<String>) = runBlocking<Unit> { // this: CoroutineScope |
| 293 | launch { |
| 294 | delay(200L) |
| 295 | println("Task from runBlocking") |
| 296 | } |
| 297 | |
| 298 | coroutineScope { // Creates a new coroutine scope |
| 299 | launch { |
| 300 | delay(500L) |
| 301 | println("Task from nested launch") |
| 302 | } |
| 303 | |
| 304 | delay(100L) |
| 305 | println("Task from coroutine scope") // This line will be printed before nested launch |
| 306 | } |
| 307 | |
| 308 | println("Coroutine scope is over") // This line is not printed until nested launch completes |
| 309 | } |
| 310 | ``` |
| 311 | |
| 312 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-04.kt) |
| 313 | |
| 314 | <!--- TEST |
| 315 | Task from coroutine scope |
| 316 | Task from runBlocking |
| 317 | Task from nested launch |
| 318 | Coroutine scope is over |
| 319 | --> |
| 320 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 321 | ### Extract function refactoring |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 322 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 323 | Let's extract the block of code inside `launch { ... }` into a separate function. When you |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 324 | perform "Extract function" refactoring on this code you get a new function with `suspend` modifier. |
| 325 | That is your first _suspending function_. Suspending functions can be used inside coroutines |
| 326 | just like regular functions, but their additional feature is that they can, in turn, |
| 327 | use other suspending functions, like `delay` in this example, to _suspend_ execution of a coroutine. |
| 328 | |
| 329 | ```kotlin |
| 330 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 331 | launch { doWorld() } |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 332 | println("Hello,") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 333 | } |
| 334 | |
| 335 | // this is your first suspending function |
| 336 | suspend fun doWorld() { |
| 337 | delay(1000L) |
| 338 | println("World!") |
| 339 | } |
| 340 | ``` |
| 341 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 342 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-05.kt) |
| 343 | |
| 344 | <!--- TEST |
| 345 | Hello, |
| 346 | World! |
| 347 | --> |
| 348 | |
| 349 | |
| 350 | But what if the extracted function contains a coroutine builder which is invoked on the current scope? |
| 351 | In this case `suspend` modifier on the extracted function is not enough. Making `doWorld` extension |
| 352 | method on `CoroutineScope` is one of the solutions, but it may not always be applicable as it does not make API clearer. |
| 353 | [currentScope] builder comes to help: it inherits current [CoroutineScope] from the coroutine context it is invoked. |
| 354 | |
| 355 | ```kotlin |
| 356 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 357 | launchDoWorld() |
| 358 | println("Hello,") |
| 359 | } |
| 360 | |
| 361 | // this is your first suspending function |
| 362 | suspend fun launchDoWorld() = currentScope { |
| 363 | launch { |
| 364 | println("World!") |
| 365 | } |
| 366 | } |
| 367 | ``` |
| 368 | |
| 369 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-05s.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 370 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 371 | <!--- TEST |
| 372 | Hello, |
| 373 | World! |
| 374 | --> |
| 375 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 376 | ### Coroutines ARE light-weight |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 377 | |
| 378 | Run the following code: |
| 379 | |
| 380 | ```kotlin |
| 381 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 382 | repeat(100_000) { // launch a lot of coroutines |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 383 | launch { |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 384 | delay(1000L) |
| 385 | print(".") |
| 386 | } |
| 387 | } |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 388 | } |
| 389 | ``` |
| 390 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 391 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-06.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 392 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 393 | <!--- TEST lines.size == 1 && lines[0] == ".".repeat(100_000) --> |
| 394 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 395 | It launches 100K coroutines and, after a second, each coroutine prints a dot. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 396 | Now, try that with threads. What would happen? (Most likely your code will produce some sort of out-of-memory error) |
| 397 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 398 | ### Global coroutines are like daemon threads |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 399 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 400 | The following code launches a long-running coroutine in [GlobalScope] that prints "I'm sleeping" twice a second and then |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 401 | returns from the main function after some delay: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 402 | |
| 403 | ```kotlin |
| 404 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 405 | GlobalScope.launch { |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 406 | repeat(1000) { i -> |
| 407 | println("I'm sleeping $i ...") |
| 408 | delay(500L) |
| 409 | } |
| 410 | } |
| 411 | delay(1300L) // just quit after delay |
| 412 | } |
| 413 | ``` |
| 414 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 415 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-07.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 416 | |
| 417 | You can run and see that it prints three lines and terminates: |
| 418 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 419 | ```text |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 420 | I'm sleeping 0 ... |
| 421 | I'm sleeping 1 ... |
| 422 | I'm sleeping 2 ... |
| 423 | ``` |
| 424 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 425 | <!--- TEST --> |
| 426 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 427 | Active coroutines that were launched in [GlobalScope] do not keep the process alive. They are like daemon threads. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 428 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 429 | ## Cancellation and timeouts |
| 430 | |
| 431 | This section covers coroutine cancellation and timeouts. |
| 432 | |
| 433 | ### Cancelling coroutine execution |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 434 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 435 | In a long-running application you might need fine-grained control on your background coroutines. |
| 436 | For example, a user might have closed the page that launched a coroutine and now its result |
| 437 | is no longer needed and its operation can be cancelled. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 438 | 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] | 439 | |
| 440 | ```kotlin |
| 441 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 442 | val job = launch { |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 443 | repeat(1000) { i -> |
| 444 | println("I'm sleeping $i ...") |
| 445 | delay(500L) |
| 446 | } |
| 447 | } |
| 448 | delay(1300L) // delay a bit |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 449 | println("main: I'm tired of waiting!") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 450 | job.cancel() // cancels the job |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 451 | job.join() // waits for job's completion |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 452 | println("main: Now I can quit.") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 453 | } |
| 454 | ``` |
| 455 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 456 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-01.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 457 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 458 | It produces the following output: |
| 459 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 460 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 461 | I'm sleeping 0 ... |
| 462 | I'm sleeping 1 ... |
| 463 | I'm sleeping 2 ... |
| 464 | main: I'm tired of waiting! |
| 465 | main: Now I can quit. |
| 466 | ``` |
| 467 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 468 | <!--- TEST --> |
| 469 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 470 | As soon as main invokes `job.cancel`, we don't see any output from the other coroutine because it was cancelled. |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 471 | There is also a [Job] extension function [cancelAndJoin] |
| 472 | that combines [cancel][Job.cancel] and [join][Job.join] invocations. |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 473 | |
| 474 | ### Cancellation is cooperative |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 475 | |
Tair Rzayev | af73462 | 2017-02-01 22:30:16 +0200 | [diff] [blame] | 476 | 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] | 477 | 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] | 478 | 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] | 479 | a computation and does not check for cancellation, then it cannot be cancelled, like the following |
| 480 | example shows: |
| 481 | |
| 482 | ```kotlin |
| 483 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 484 | val startTime = System.currentTimeMillis() |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 485 | val job = launch(Dispatchers.Default) { |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 486 | var nextPrintTime = startTime |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 487 | var i = 0 |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 488 | while (i < 5) { // computation loop, just wastes CPU |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 489 | // print a message twice a second |
| 490 | if (System.currentTimeMillis() >= nextPrintTime) { |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 491 | println("I'm sleeping ${i++} ...") |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 492 | nextPrintTime += 500L |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 493 | } |
| 494 | } |
| 495 | } |
| 496 | delay(1300L) // delay a bit |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 497 | println("main: I'm tired of waiting!") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 498 | job.cancelAndJoin() // cancels the job and waits for its completion |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 499 | println("main: Now I can quit.") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 500 | } |
| 501 | ``` |
| 502 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 503 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-02.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 504 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 505 | Run it to see that it continues to print "I'm sleeping" even after cancellation |
| 506 | until the job completes by itself after five iterations. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 507 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 508 | <!--- TEST |
| 509 | I'm sleeping 0 ... |
| 510 | I'm sleeping 1 ... |
| 511 | I'm sleeping 2 ... |
| 512 | main: I'm tired of waiting! |
| 513 | I'm sleeping 3 ... |
| 514 | I'm sleeping 4 ... |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 515 | main: Now I can quit. |
| 516 | --> |
| 517 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 518 | ### Making computation code cancellable |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 519 | |
| 520 | There are two approaches to making computation code cancellable. The first one is to periodically |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 521 | invoke a suspending function that checks for cancellation. 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] | 522 | 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] | 523 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 524 | Replace `while (i < 5)` in the previous example with `while (isActive)` and rerun it. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 525 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 526 | ```kotlin |
| 527 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 528 | val startTime = System.currentTimeMillis() |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 529 | val job = launch(Dispatchers.Default) { |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 530 | var nextPrintTime = startTime |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 531 | var i = 0 |
| 532 | while (isActive) { // cancellable computation loop |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 533 | // print a message twice a second |
| 534 | if (System.currentTimeMillis() >= nextPrintTime) { |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 535 | println("I'm sleeping ${i++} ...") |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 536 | nextPrintTime += 500L |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 537 | } |
| 538 | } |
| 539 | } |
| 540 | delay(1300L) // delay a bit |
| 541 | println("main: I'm tired of waiting!") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 542 | job.cancelAndJoin() // cancels the job and waits for its completion |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 543 | println("main: Now I can quit.") |
| 544 | } |
| 545 | ``` |
| 546 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 547 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-03.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 548 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 549 | As you can see, now this loop is cancelled. [isActive] is an extension property that is |
| 550 | available inside the code of coroutine via [CoroutineScope] object. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 551 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 552 | <!--- TEST |
| 553 | I'm sleeping 0 ... |
| 554 | I'm sleeping 1 ... |
| 555 | I'm sleeping 2 ... |
| 556 | main: I'm tired of waiting! |
| 557 | main: Now I can quit. |
| 558 | --> |
| 559 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 560 | ### Closing resources with finally |
| 561 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 562 | Cancellable suspending functions throw [CancellationException] on cancellation which can be handled in |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 563 | a usual way. For example, `try {...} finally {...}` expression and Kotlin `use` function execute their |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 564 | finalization actions normally when coroutine is cancelled: |
| 565 | |
| 566 | ```kotlin |
| 567 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 568 | val job = launch { |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 569 | try { |
| 570 | repeat(1000) { i -> |
| 571 | println("I'm sleeping $i ...") |
| 572 | delay(500L) |
| 573 | } |
| 574 | } finally { |
| 575 | println("I'm running finally") |
| 576 | } |
| 577 | } |
| 578 | delay(1300L) // delay a bit |
| 579 | println("main: I'm tired of waiting!") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 580 | job.cancelAndJoin() // cancels the job and waits for its completion |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 581 | println("main: Now I can quit.") |
| 582 | } |
| 583 | ``` |
| 584 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 585 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-04.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 586 | |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 587 | Both [join][Job.join] and [cancelAndJoin] wait for all the finalization actions to complete, |
| 588 | so the example above produces the following output: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 589 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 590 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 591 | I'm sleeping 0 ... |
| 592 | I'm sleeping 1 ... |
| 593 | I'm sleeping 2 ... |
| 594 | main: I'm tired of waiting! |
| 595 | I'm running finally |
| 596 | main: Now I can quit. |
| 597 | ``` |
| 598 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 599 | <!--- TEST --> |
| 600 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 601 | ### Run non-cancellable block |
| 602 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 603 | Any attempt to use a suspending function in the `finally` block of the previous example causes |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 604 | [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] | 605 | problem, since all well-behaving closing operations (closing a file, cancelling a job, or closing any kind of a |
| 606 | communication channel) are usually non-blocking and do not involve any suspending functions. However, in the |
| 607 | rare case when you need to suspend in the cancelled coroutine you can wrap the corresponding code in |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 608 | `withContext(NonCancellable) {...}` using [withContext] function and [NonCancellable] context as the following example shows: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 609 | |
| 610 | ```kotlin |
| 611 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 612 | val job = launch { |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 613 | try { |
| 614 | repeat(1000) { i -> |
| 615 | println("I'm sleeping $i ...") |
| 616 | delay(500L) |
| 617 | } |
| 618 | } finally { |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 619 | withContext(NonCancellable) { |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 620 | println("I'm running finally") |
| 621 | delay(1000L) |
| 622 | println("And I've just delayed for 1 sec because I'm non-cancellable") |
| 623 | } |
| 624 | } |
| 625 | } |
| 626 | delay(1300L) // delay a bit |
| 627 | println("main: I'm tired of waiting!") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 628 | job.cancelAndJoin() // cancels the job and waits for its completion |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 629 | println("main: Now I can quit.") |
| 630 | } |
| 631 | ``` |
| 632 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 633 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-05.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 634 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 635 | <!--- TEST |
| 636 | I'm sleeping 0 ... |
| 637 | I'm sleeping 1 ... |
| 638 | I'm sleeping 2 ... |
| 639 | main: I'm tired of waiting! |
| 640 | I'm running finally |
| 641 | And I've just delayed for 1 sec because I'm non-cancellable |
| 642 | main: Now I can quit. |
| 643 | --> |
| 644 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 645 | ### Timeout |
| 646 | |
Brad | 977ada1 | 2018-07-19 16:01:40 -0400 | [diff] [blame] | 647 | The most obvious reason to cancel coroutine execution in practice |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 648 | is because its execution time has exceeded some timeout. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 649 | While you can manually track the reference to the corresponding [Job] and launch a separate coroutine to cancel |
| 650 | 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] | 651 | Look at the following example: |
| 652 | |
| 653 | ```kotlin |
| 654 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 655 | withTimeout(1300L) { |
| 656 | repeat(1000) { i -> |
| 657 | println("I'm sleeping $i ...") |
| 658 | delay(500L) |
| 659 | } |
| 660 | } |
| 661 | } |
| 662 | ``` |
| 663 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 664 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-06.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 665 | |
| 666 | It produces the following output: |
| 667 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 668 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 669 | I'm sleeping 0 ... |
| 670 | I'm sleeping 1 ... |
| 671 | I'm sleeping 2 ... |
Roman Elizarov | 63f6ea2 | 2017-09-06 18:42:34 +0300 | [diff] [blame] | 672 | Exception in thread "main" kotlinx.coroutines.experimental.TimeoutCancellationException: Timed out waiting for 1300 MILLISECONDS |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 673 | ``` |
| 674 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 675 | <!--- TEST STARTS_WITH --> |
| 676 | |
Roman Elizarov | 63f6ea2 | 2017-09-06 18:42:34 +0300 | [diff] [blame] | 677 | The `TimeoutCancellationException` that is thrown by [withTimeout] is a subclass of [CancellationException]. |
Roman Elizarov | ca9d5be | 2017-04-20 19:23:18 +0300 | [diff] [blame] | 678 | 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] | 679 | 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] | 680 | However, in this example we have used `withTimeout` right inside the `main` function. |
| 681 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 682 | Because cancellation is just an exception, all the resources are closed in a usual way. |
Roman Elizarov | 63f6ea2 | 2017-09-06 18:42:34 +0300 | [diff] [blame] | 683 | You can wrap the code with timeout in `try {...} catch (e: TimeoutCancellationException) {...}` block if |
| 684 | you need to do some additional action specifically on any kind of timeout or use [withTimeoutOrNull] function |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 685 | that is similar to [withTimeout], but returns `null` on timeout instead of throwing an exception: |
| 686 | |
| 687 | ```kotlin |
| 688 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 689 | val result = withTimeoutOrNull(1300L) { |
| 690 | repeat(1000) { i -> |
| 691 | println("I'm sleeping $i ...") |
| 692 | delay(500L) |
| 693 | } |
| 694 | "Done" // will get cancelled before it produces this result |
| 695 | } |
| 696 | println("Result is $result") |
| 697 | } |
| 698 | ``` |
| 699 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 700 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-07.kt) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 701 | |
| 702 | There is no longer an exception when running this code: |
| 703 | |
| 704 | ```text |
| 705 | I'm sleeping 0 ... |
| 706 | I'm sleeping 1 ... |
| 707 | I'm sleeping 2 ... |
| 708 | Result is null |
| 709 | ``` |
| 710 | |
| 711 | <!--- TEST --> |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 712 | |
| 713 | ## Composing suspending functions |
| 714 | |
| 715 | This section covers various approaches to composition of suspending functions. |
| 716 | |
| 717 | ### Sequential by default |
| 718 | |
| 719 | 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] | 720 | remote service call or computation. We just pretend they are useful, but actually each one just |
| 721 | delays for a second for the purpose of this example: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 722 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 723 | <!--- INCLUDE .*/example-compose-([0-9]+).kt |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 724 | import kotlin.system.* |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 725 | --> |
| 726 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 727 | ```kotlin |
| 728 | suspend fun doSomethingUsefulOne(): Int { |
| 729 | delay(1000L) // pretend we are doing something useful here |
| 730 | return 13 |
| 731 | } |
| 732 | |
| 733 | suspend fun doSomethingUsefulTwo(): Int { |
| 734 | delay(1000L) // pretend we are doing something useful here, too |
| 735 | return 29 |
| 736 | } |
| 737 | ``` |
| 738 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 739 | <!--- INCLUDE .*/example-compose-([0-9]+).kt --> |
| 740 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 741 | What do we do if need to invoke them _sequentially_ -- first `doSomethingUsefulOne` _and then_ |
| 742 | `doSomethingUsefulTwo` and compute the sum of their results? |
Ronen Sabag | d2d42ea | 2017-12-24 21:55:06 +0200 | [diff] [blame] | 743 | In practice we do this if we use the results of the first function to make a decision on whether we need |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 744 | to invoke the second one or to decide on how to invoke it. |
| 745 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 746 | We 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] | 747 | 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] | 748 | time it takes to execute both suspending functions: |
| 749 | |
| 750 | ```kotlin |
| 751 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 752 | val time = measureTimeMillis { |
| 753 | val one = doSomethingUsefulOne() |
| 754 | val two = doSomethingUsefulTwo() |
| 755 | println("The answer is ${one + two}") |
| 756 | } |
| 757 | println("Completed in $time ms") |
| 758 | } |
| 759 | ``` |
| 760 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 761 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-compose-01.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 762 | |
| 763 | It produces something like this: |
| 764 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 765 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 766 | The answer is 42 |
| 767 | Completed in 2017 ms |
| 768 | ``` |
| 769 | |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 770 | <!--- TEST ARBITRARY_TIME --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 771 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 772 | ### Concurrent using async |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 773 | |
| 774 | 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] | 775 | 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] | 776 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 777 | Conceptually, [async] is just like [launch]. It starts a separate coroutine which is a light-weight thread |
| 778 | that works concurrently with all the other coroutines. The difference is that `launch` returns a [Job] and |
| 779 | 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] | 780 | 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] | 781 | but `Deferred` is also a `Job`, so you can cancel it if needed. |
| 782 | |
| 783 | ```kotlin |
| 784 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 785 | val time = measureTimeMillis { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 786 | val one = async { doSomethingUsefulOne() } |
| 787 | val two = async { doSomethingUsefulTwo() } |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 788 | println("The answer is ${one.await() + two.await()}") |
| 789 | } |
| 790 | println("Completed in $time ms") |
| 791 | } |
| 792 | ``` |
| 793 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 794 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-compose-02.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 795 | |
| 796 | It produces something like this: |
| 797 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 798 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 799 | The answer is 42 |
| 800 | Completed in 1017 ms |
| 801 | ``` |
| 802 | |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 803 | <!--- TEST ARBITRARY_TIME --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 804 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 805 | This is twice as fast, because we have concurrent execution of two coroutines. |
| 806 | Note, that concurrency with coroutines is always explicit. |
| 807 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 808 | ### Lazily started async |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 809 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 810 | There is a laziness option to [async] using an optional `start` parameter with a value of [CoroutineStart.LAZY]. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 811 | It starts coroutine only when its result is needed by some |
| 812 | [await][Deferred.await] or if a [start][Job.start] function |
Sahil Lone | 52a0ec0 | 2018-07-19 18:55:35 +0200 | [diff] [blame] | 813 | is invoked. Run the following example: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 814 | |
| 815 | ```kotlin |
| 816 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 817 | val time = measureTimeMillis { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 818 | val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() } |
| 819 | val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() } |
Sahil Lone | 52a0ec0 | 2018-07-19 18:55:35 +0200 | [diff] [blame] | 820 | // some computation |
| 821 | one.start() // start the first one |
| 822 | two.start() // start the second one |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 823 | println("The answer is ${one.await() + two.await()}") |
| 824 | } |
| 825 | println("Completed in $time ms") |
| 826 | } |
| 827 | ``` |
| 828 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 829 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-compose-03.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 830 | |
| 831 | It produces something like this: |
| 832 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 833 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 834 | The answer is 42 |
Sahil Lone | 52a0ec0 | 2018-07-19 18:55:35 +0200 | [diff] [blame] | 835 | Completed in 1017 ms |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 836 | ``` |
| 837 | |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 838 | <!--- TEST ARBITRARY_TIME --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 839 | |
Sahil Lone | 52a0ec0 | 2018-07-19 18:55:35 +0200 | [diff] [blame] | 840 | So, here the two coroutines are defined but not executed as in the previous example, but the control is given to |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 841 | the programmer on when exactly to start the execution by calling [start][Job.start]. We first |
Sahil Lone | 52a0ec0 | 2018-07-19 18:55:35 +0200 | [diff] [blame] | 842 | start `one`, then start `two`, and then await for the individual coroutines to finish. |
| 843 | |
| 844 | Note, that if we have called [await][Deferred.await] in `println` and omitted [start][Job.start] on individual |
| 845 | coroutines, then we would have got the sequential behaviour as [await][Deferred.await] starts the coroutine |
| 846 | execution and waits for the execution to finish, which is not the intended use-case for laziness. |
| 847 | The use-case for `async(start = CoroutineStart.LAZY)` is a replacement for the |
| 848 | standard `lazy` function in cases when computation of the value involves suspending functions. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 849 | |
| 850 | ### Async-style functions |
| 851 | |
| 852 | We can define async-style functions that invoke `doSomethingUsefulOne` and `doSomethingUsefulTwo` |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 853 | _asynchronously_ using [async] coroutine builder with an explicit [GlobalScope] reference. |
| 854 | We name such functions with |
Marcin Moskała | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 855 | "Async" suffix to highlight the fact that they only start asynchronous computation and one needs |
| 856 | to use the resulting deferred value to get the result. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 857 | |
| 858 | ```kotlin |
Marcin Moskała | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 859 | // The result type of somethingUsefulOneAsync is Deferred<Int> |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 860 | fun somethingUsefulOneAsync() = GlobalScope.async { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 861 | doSomethingUsefulOne() |
| 862 | } |
| 863 | |
Marcin Moskała | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 864 | // The result type of somethingUsefulTwoAsync is Deferred<Int> |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 865 | fun somethingUsefulTwoAsync() = GlobalScope.async { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 866 | doSomethingUsefulTwo() |
| 867 | } |
| 868 | ``` |
| 869 | |
Marcin Moskała | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 870 | Note, that these `xxxAsync` functions are **not** _suspending_ functions. They can be used from anywhere. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 871 | However, their use always implies asynchronous (here meaning _concurrent_) execution of their action |
| 872 | with the invoking code. |
| 873 | |
| 874 | The following example shows their use outside of coroutine: |
| 875 | |
| 876 | ```kotlin |
| 877 | // note, that we don't have `runBlocking` to the right of `main` in this example |
| 878 | fun main(args: Array<String>) { |
| 879 | val time = measureTimeMillis { |
| 880 | // we can initiate async actions outside of a coroutine |
Marcin Moskała | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 881 | val one = somethingUsefulOneAsync() |
| 882 | val two = somethingUsefulTwoAsync() |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 883 | // but waiting for a result must involve either suspending or blocking. |
| 884 | // here we use `runBlocking { ... }` to block the main thread while waiting for the result |
| 885 | runBlocking { |
| 886 | println("The answer is ${one.await() + two.await()}") |
| 887 | } |
| 888 | } |
| 889 | println("Completed in $time ms") |
| 890 | } |
| 891 | ``` |
| 892 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 893 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-compose-04.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 894 | |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 895 | <!--- TEST ARBITRARY_TIME |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 896 | The answer is 42 |
| 897 | Completed in 1085 ms |
| 898 | --> |
| 899 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 900 | > This programming style with async functions is provided here only for illustration, because it is a popular style |
| 901 | in other programming languages. Using this style with Kotlin coroutines is **strongly discouraged** for the |
| 902 | reasons that are explained below. |
| 903 | |
| 904 | Consider what happens if between `val one = somethingUsefulOneAsync()` line and `one.await()` expression there is some logic |
| 905 | error in the code and the program throws an exception and the operation that was being performed by the program aborts. |
| 906 | Normally, a global error-handler could catch this exception, log and report the error for developers, but the program |
| 907 | could otherwise continue doing other operations. But here we have `somethingUsefulOneAsync` still running in background, |
| 908 | despite the fact, that operation that had initiated it aborts. This problem does not happen with structured |
| 909 | concurrency, as shown in the section below. |
| 910 | |
| 911 | ### Structured concurrency with async |
| 912 | |
| 913 | Let us take [Concurrent using async](#concurrent-using-async) example and extract a function that |
| 914 | concurrently performs `doSomethingUsefulOne` and `doSomethingUsefulOne` and returns the sum of their results. |
| 915 | Because [async] coroutines builder is defined as extension on [CoroutineScope] we need to have it in the |
| 916 | scope and that is what [coroutineScope] function provides: |
| 917 | |
| 918 | ```kotlin |
| 919 | suspend fun concurrentSum(): Int = coroutineScope { |
| 920 | val one = async { doSomethingUsefulOne() } |
| 921 | val two = async { doSomethingUsefulTwo() } |
| 922 | awaitAll(one, two) |
| 923 | one.await() + two.await() |
| 924 | } |
| 925 | ``` |
| 926 | |
| 927 | This way, if something goes wrong inside the code of `concurrentSum` function and it throws an exception, |
| 928 | all the coroutines that were launched in its scope are cancelled. |
| 929 | |
| 930 | ```kotlin |
| 931 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 932 | val time = measureTimeMillis { |
| 933 | println("The answer is ${concurrentSum()}") |
| 934 | } |
| 935 | println("Completed in $time ms") |
| 936 | } |
| 937 | ``` |
| 938 | |
| 939 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-compose-05.kt) |
| 940 | |
| 941 | We still have concurrent execution of both operations as evident from the output of the above main function: |
| 942 | |
| 943 | ```text |
| 944 | The answer is 42 |
| 945 | Completed in 1017 ms |
| 946 | ``` |
| 947 | |
| 948 | <!--- TEST ARBITRARY_TIME --> |
| 949 | |
| 950 | Cancellation is always propagated through coroutines hierarchy: |
| 951 | |
| 952 | ```kotlin |
| 953 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 954 | try { |
| 955 | failedConcurrentSum() |
| 956 | } catch(e: ArithmeticException) { |
| 957 | println("Computation failed with ArithmeticException") |
| 958 | } |
| 959 | } |
| 960 | |
| 961 | suspend fun failedConcurrentSum(): Int = coroutineScope { |
| 962 | val one = async<Int> { |
| 963 | try { |
| 964 | delay(Long.MAX_VALUE) // Emulates very long computation |
| 965 | 42 |
| 966 | } finally { |
| 967 | println("First child was cancelled") |
| 968 | } |
| 969 | } |
| 970 | val two = async<Int> { |
| 971 | println("Second child throws an exception") |
| 972 | throw ArithmeticException() |
| 973 | } |
| 974 | |
| 975 | awaitAll(one, two) |
| 976 | one.await() + two.await() |
| 977 | } |
| 978 | ``` |
| 979 | |
| 980 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-compose-06.kt) |
| 981 | |
| 982 | Note, how both first `async` and awaiting parent are cancelled on the one child failure: |
| 983 | ```text |
| 984 | Second child throws an exception |
| 985 | First child was cancelled |
| 986 | Computation failed with ArithmeticException |
| 987 | ``` |
| 988 | |
| 989 | <!--- TEST --> |
| 990 | |
| 991 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 992 | ## Coroutine context and dispatchers |
| 993 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 994 | Coroutines always execute in some context which is represented by the value of |
| 995 | [CoroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/-coroutine-context/) |
| 996 | type, defined in the Kotlin standard library. |
| 997 | |
| 998 | The coroutine context is a set of various elements. The main elements are the [Job] of the coroutine, |
| 999 | which we've seen before, and its dispatcher, which is covered in this section. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1000 | |
| 1001 | ### Dispatchers and threads |
| 1002 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1003 | Coroutine context includes a _coroutine dispatcher_ (see [CoroutineDispatcher]) that determines what thread or threads |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1004 | the corresponding coroutine uses for its execution. Coroutine dispatcher can confine coroutine execution |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1005 | to a specific thread, dispatch it to a thread pool, or let it run unconfined. |
| 1006 | |
| 1007 | All coroutines builders like [launch] and [async] accept an optional |
| 1008 | [CoroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/-coroutine-context/) |
| 1009 | parameter that can be used to explicitly specify the dispatcher for new coroutine and other context elements. |
| 1010 | |
| 1011 | Try the following example: |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1012 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1013 | <!--- INCLUDE |
| 1014 | import kotlin.coroutines.experimental.* |
| 1015 | --> |
| 1016 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1017 | ```kotlin |
| 1018 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1019 | launch { // context of the parent, main runBlocking coroutine |
| 1020 | println("main runBlocking : I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1021 | } |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1022 | launch(Dispatchers.Unconfined) { // not confined -- will work with main thread |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1023 | println("Unconfined : I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1024 | } |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1025 | launch(Dispatchers.Default) { // will get dispatched to ForkJoinPool.commonPool (or equivalent) |
| 1026 | println("Default : I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1027 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1028 | launch(newSingleThreadContext("MyOwnThread")) { // will get its own new thread |
| 1029 | println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1030 | } |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1031 | } |
| 1032 | ``` |
| 1033 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1034 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-01.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1035 | |
| 1036 | It produces the following output (maybe in different order): |
| 1037 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1038 | ```text |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1039 | Unconfined : I'm working in thread main |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1040 | Default : I'm working in thread CommonPool-worker-1 |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1041 | newSingleThreadContext: I'm working in thread MyOwnThread |
| 1042 | main runBlocking : I'm working in thread main |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1043 | ``` |
| 1044 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1045 | <!--- TEST LINES_START_UNORDERED --> |
| 1046 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1047 | When `launch { ... }` is used without parameters, it inherits the context (and thus dispatcher) |
| 1048 | from the [CoroutineScope] that it is being launched from. In this case, it inherits the |
| 1049 | context of the main `runBlocking` coroutine which runs in the `main` thread. |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1050 | |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1051 | [Dispatchers.Unconfined] is a special dispatcher that also appears to run in the `main` thread, but it is, |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1052 | in fact, a different mechanism that is explained later. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1053 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1054 | The default dispatcher, that is used when coroutines are launched in [GlobalScope], |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1055 | is represented by [Dispatchers.Default] and uses shared background pool of threads, |
| 1056 | so `launch(Dispatchers.Default) { ... }` uses the same dispatcher as `GlobalScope.launch { ... }`. |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1057 | |
| 1058 | [newSingleThreadContext] creates a new thread for the coroutine to run. |
| 1059 | A dedicated thread is a very expensive resource. |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 1060 | In a real application it must be either released, when no longer needed, using [close][ThreadPoolDispatcher.close] |
| 1061 | function, or stored in a top-level variable and reused throughout the application. |
| 1062 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1063 | ### Unconfined vs confined dispatcher |
| 1064 | |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1065 | The [Dispatchers.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] | 1066 | first suspension point. After suspension it resumes in the thread that is fully determined by the |
| 1067 | suspending function that was invoked. Unconfined dispatcher is appropriate when coroutine does not |
| 1068 | consume CPU time nor updates any shared data (like UI) that is confined to a specific thread. |
| 1069 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1070 | On the other side, by default, a dispatcher for the outer [CoroutineScope] is inherited. |
| 1071 | The default dispatcher for [runBlocking] coroutine, in particular, |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1072 | is confined to the invoker thread, so inheriting it has the effect of confining execution to |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1073 | this thread with a predictable FIFO scheduling. |
| 1074 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1075 | <!--- INCLUDE |
| 1076 | import kotlin.coroutines.experimental.* |
| 1077 | --> |
| 1078 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1079 | ```kotlin |
| 1080 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1081 | launch(Dispatchers.Unconfined) { // not confined -- will work with main thread |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1082 | println("Unconfined : I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | d002162 | 2017-03-10 15:43:38 +0300 | [diff] [blame] | 1083 | delay(500) |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1084 | println("Unconfined : After delay in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1085 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1086 | launch { // context of the parent, main runBlocking coroutine |
| 1087 | println("main runBlocking: I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1088 | delay(1000) |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1089 | println("main runBlocking: After delay in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1090 | } |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1091 | } |
| 1092 | ``` |
| 1093 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1094 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-02.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1095 | |
| 1096 | Produces the output: |
| 1097 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1098 | ```text |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1099 | Unconfined : I'm working in thread main |
| 1100 | main runBlocking: I'm working in thread main |
| 1101 | Unconfined : After delay in thread kotlinx.coroutines.DefaultExecutor |
| 1102 | main runBlocking: After delay in thread main |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1103 | ``` |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1104 | |
| 1105 | <!--- TEST LINES_START --> |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1106 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1107 | So, the coroutine that had inherited context of `runBlocking {...}` continues to execute |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1108 | in the `main` thread, while the unconfined one had resumed in the default executor thread that [delay] |
| 1109 | function is using. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1110 | |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1111 | > Unconfined dispatcher is an advanced mechanism that can be helpful in certain corner cases where |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1112 | dispatching of coroutine for its execution later is not needed or produces undesirable side-effects, |
| 1113 | because some operation in a coroutine must be performed right away. |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1114 | Unconfined dispatcher should not be used in general code. |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1115 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1116 | ### Debugging coroutines and threads |
| 1117 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1118 | Coroutines can suspend on one thread and resume on another thread. |
| 1119 | Even with a single-threaded dispatcher it might be hard to |
paolop | b019b10 | 2018-06-09 16:42:24 +0000 | [diff] [blame] | 1120 | figure out what coroutine was doing, where, and when. The common approach to debugging applications with |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1121 | threads is to print the thread name in the log file on each log statement. This feature is universally supported |
| 1122 | by logging frameworks. When using coroutines, the thread name alone does not give much of a context, so |
| 1123 | `kotlinx.coroutines` includes debugging facilities to make it easier. |
| 1124 | |
| 1125 | Run the following code with `-Dkotlinx.coroutines.debug` JVM option: |
| 1126 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1127 | <!--- INCLUDE |
| 1128 | import kotlin.coroutines.experimental.* |
| 1129 | --> |
| 1130 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1131 | ```kotlin |
| 1132 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 1133 | |
| 1134 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1135 | val a = async { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1136 | log("I'm computing a piece of the answer") |
| 1137 | 6 |
| 1138 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1139 | val b = async { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1140 | log("I'm computing another piece of the answer") |
| 1141 | 7 |
| 1142 | } |
| 1143 | log("The answer is ${a.await() * b.await()}") |
| 1144 | } |
| 1145 | ``` |
| 1146 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1147 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-03.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1148 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1149 | There are three coroutines. The main coroutine (#1) -- `runBlocking` one, |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1150 | and two coroutines computing deferred values `a` (#2) and `b` (#3). |
| 1151 | They are all executing in the context of `runBlocking` and are confined to the main thread. |
| 1152 | The output of this code is: |
| 1153 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1154 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1155 | [main @coroutine#2] I'm computing a piece of the answer |
| 1156 | [main @coroutine#3] I'm computing another piece of the answer |
| 1157 | [main @coroutine#1] The answer is 42 |
| 1158 | ``` |
| 1159 | |
Kirill Timofeev | a518696 | 2017-10-25 14:25:47 +0300 | [diff] [blame] | 1160 | <!--- TEST FLEXIBLE_THREAD --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1161 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1162 | The `log` function prints the name of the thread in square brackets and you can see, that it is the `main` |
| 1163 | thread, but the identifier of the currently executing coroutine is appended to it. This identifier |
| 1164 | is consecutively assigned to all created coroutines when debugging mode is turned on. |
| 1165 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1166 | 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] | 1167 | |
| 1168 | ### Jumping between threads |
| 1169 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1170 | Run the following code with `-Dkotlinx.coroutines.debug` JVM option (see [debug](#debugging-coroutines-and-threads)): |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1171 | |
| 1172 | ```kotlin |
| 1173 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 1174 | |
| 1175 | fun main(args: Array<String>) { |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 1176 | newSingleThreadContext("Ctx1").use { ctx1 -> |
| 1177 | newSingleThreadContext("Ctx2").use { ctx2 -> |
| 1178 | runBlocking(ctx1) { |
| 1179 | log("Started in ctx1") |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 1180 | withContext(ctx2) { |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 1181 | log("Working in ctx2") |
| 1182 | } |
| 1183 | log("Back to ctx1") |
| 1184 | } |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1185 | } |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1186 | } |
| 1187 | } |
| 1188 | ``` |
| 1189 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1190 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-04.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1191 | |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 1192 | It demonstrates several new techniques. One is using [runBlocking] with an explicitly specified context, and |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 1193 | the other one is using [withContext] 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] | 1194 | same coroutine as you can see in the output below: |
| 1195 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1196 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1197 | [Ctx1 @coroutine#1] Started in ctx1 |
| 1198 | [Ctx2 @coroutine#1] Working in ctx2 |
| 1199 | [Ctx1 @coroutine#1] Back to ctx1 |
| 1200 | ``` |
| 1201 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1202 | <!--- TEST --> |
| 1203 | |
Artsiom Chapialiou | e185ed6 | 2018-06-03 19:34:22 -0400 | [diff] [blame] | 1204 | Note, that this example also uses `use` function from the Kotlin standard library to release threads that |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 1205 | are created with [newSingleThreadContext] when they are no longer needed. |
| 1206 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1207 | ### Job in the context |
| 1208 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1209 | The coroutine's [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] | 1210 | using `coroutineContext[Job]` expression: |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1211 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1212 | <!--- INCLUDE |
| 1213 | import kotlin.coroutines.experimental.* |
| 1214 | --> |
| 1215 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1216 | ```kotlin |
| 1217 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1218 | println("My job is ${coroutineContext[Job]}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1219 | } |
| 1220 | ``` |
| 1221 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1222 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-05.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1223 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1224 | It produces something like that when running in [debug mode](#debugging-coroutines-and-threads): |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1225 | |
| 1226 | ``` |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1227 | My job is "coroutine#1":BlockingCoroutine{Active}@6d311334 |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1228 | ``` |
| 1229 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1230 | <!--- TEST lines.size == 1 && lines[0].startsWith("My job is \"coroutine#1\":BlockingCoroutine{Active}@") --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1231 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1232 | Note, that [isActive] in [CoroutineScope] is just a convenient shortcut for |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1233 | `coroutineContext[Job]?.isActive == true`. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1234 | |
| 1235 | ### Children of a coroutine |
| 1236 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1237 | When a coroutine is launched in the [CoroutineScope] of another coroutine, |
| 1238 | it inherits its context via [CoroutineScope.coroutineContext] and |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1239 | the [Job] of the new coroutine becomes |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1240 | a _child_ of the parent coroutine's job. When the parent coroutine is cancelled, all its children |
| 1241 | are recursively cancelled, too. |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1242 | |
| 1243 | However, when [GlobalScope] is used to launch a coroutine, it is not tied to the scope it |
| 1244 | was launched from and operates independently. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1245 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1246 | <!--- INCLUDE |
| 1247 | import kotlin.coroutines.experimental.* |
| 1248 | --> |
| 1249 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1250 | ```kotlin |
| 1251 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1252 | // launch a coroutine to process some kind of incoming request |
| 1253 | val request = launch { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1254 | // it spawns two other jobs, one with GlobalScope |
| 1255 | GlobalScope.launch { |
| 1256 | println("job1: I run in GlobalScope and execute independently!") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1257 | delay(1000) |
| 1258 | println("job1: I am not affected by cancellation of the request") |
| 1259 | } |
| 1260 | // and the other inherits the parent context |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1261 | launch { |
Roman Elizarov | 74619c1 | 2017-11-09 10:32:15 +0300 | [diff] [blame] | 1262 | delay(100) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1263 | println("job2: I am a child of the request coroutine") |
| 1264 | delay(1000) |
| 1265 | println("job2: I will not execute this line if my parent request is cancelled") |
| 1266 | } |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1267 | } |
| 1268 | delay(500) |
| 1269 | request.cancel() // cancel processing of the request |
| 1270 | delay(1000) // delay a second to see what happens |
| 1271 | println("main: Who has survived request cancellation?") |
| 1272 | } |
| 1273 | ``` |
| 1274 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1275 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-06.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1276 | |
| 1277 | The output of this code is: |
| 1278 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1279 | ```text |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1280 | job1: I run in GlobalScope and execute independently! |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1281 | job2: I am a child of the request coroutine |
| 1282 | job1: I am not affected by cancellation of the request |
| 1283 | main: Who has survived request cancellation? |
| 1284 | ``` |
| 1285 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1286 | <!--- TEST --> |
| 1287 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1288 | ### Parental responsibilities |
| 1289 | |
| 1290 | A parent coroutine always waits for completion of all its children. Parent does not have to explicitly track |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 1291 | all the children it launches and it does not have to use [Job.join] to wait for them at the end: |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1292 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1293 | <!--- INCLUDE |
| 1294 | import kotlin.coroutines.experimental.* |
| 1295 | --> |
| 1296 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1297 | ```kotlin |
| 1298 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1299 | // launch a coroutine to process some kind of incoming request |
| 1300 | val request = launch { |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1301 | repeat(3) { i -> // launch a few children jobs |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1302 | launch { |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1303 | delay((i + 1) * 200L) // variable delay 200ms, 400ms, 600ms |
| 1304 | println("Coroutine $i is done") |
| 1305 | } |
| 1306 | } |
| 1307 | println("request: I'm done and I don't explicitly join my children that are still active") |
| 1308 | } |
| 1309 | request.join() // wait for completion of the request, including all its children |
| 1310 | println("Now processing of the request is complete") |
| 1311 | } |
| 1312 | ``` |
| 1313 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1314 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-07.kt) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1315 | |
| 1316 | The result is going to be: |
| 1317 | |
| 1318 | ```text |
| 1319 | request: I'm done and I don't explicitly join my children that are still active |
| 1320 | Coroutine 0 is done |
| 1321 | Coroutine 1 is done |
| 1322 | Coroutine 2 is done |
| 1323 | Now processing of the request is complete |
| 1324 | ``` |
| 1325 | |
| 1326 | <!--- TEST --> |
| 1327 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1328 | ### Naming coroutines for debugging |
| 1329 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1330 | 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] | 1331 | coming from the same coroutine. However, when coroutine is tied to the processing of a specific request |
| 1332 | or doing some specific background task, it is better to name it explicitly for debugging purposes. |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1333 | [CoroutineName] context element serves the same function as a thread name. It'll get displayed in the thread name that |
| 1334 | is executing this coroutine when [debugging mode](#debugging-coroutines-and-threads) is turned on. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1335 | |
| 1336 | The following example demonstrates this concept: |
| 1337 | |
| 1338 | ```kotlin |
| 1339 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 1340 | |
| 1341 | fun main(args: Array<String>) = runBlocking(CoroutineName("main")) { |
| 1342 | log("Started main coroutine") |
| 1343 | // run two background value computations |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1344 | val v1 = async(CoroutineName("v1coroutine")) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1345 | delay(500) |
Roman Elizarov | 674efea | 2017-10-21 17:16:30 +0300 | [diff] [blame] | 1346 | log("Computing v1") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1347 | 252 |
| 1348 | } |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1349 | val v2 = async(CoroutineName("v2coroutine")) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1350 | delay(1000) |
Roman Elizarov | 674efea | 2017-10-21 17:16:30 +0300 | [diff] [blame] | 1351 | log("Computing v2") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1352 | 6 |
| 1353 | } |
| 1354 | log("The answer for v1 / v2 = ${v1.await() / v2.await()}") |
| 1355 | } |
| 1356 | ``` |
| 1357 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1358 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-08.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1359 | |
| 1360 | The output it produces with `-Dkotlinx.coroutines.debug` JVM option is similar to: |
| 1361 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1362 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1363 | [main @main#1] Started main coroutine |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1364 | [main @v1coroutine#2] Computing v1 |
| 1365 | [main @v2coroutine#3] Computing v2 |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1366 | [main @main#1] The answer for v1 / v2 = 42 |
| 1367 | ``` |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 1368 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1369 | <!--- TEST FLEXIBLE_THREAD --> |
| 1370 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1371 | ### Combining context elements |
| 1372 | |
| 1373 | Sometimes we need to define multiple elements for coroutine context. We can use `+` operator for that. |
| 1374 | For example, we can launch a coroutine with an explicitly specified dispatcher and an explicitly specified |
| 1375 | name at the same time: |
| 1376 | |
| 1377 | <!--- INCLUDE |
| 1378 | import kotlin.coroutines.experimental.* |
| 1379 | --> |
| 1380 | |
| 1381 | ```kotlin |
| 1382 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1383 | launch(Dispatchers.Default + CoroutineName("test")) { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1384 | println("I'm working in thread ${Thread.currentThread().name}") |
| 1385 | } |
| 1386 | } |
| 1387 | ``` |
| 1388 | |
| 1389 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-09.kt) |
| 1390 | |
| 1391 | The output of this code with `-Dkotlinx.coroutines.debug` JVM option is: |
| 1392 | |
| 1393 | ```text |
| 1394 | I'm working in thread CommonPool-worker-1 @test#2 |
| 1395 | ``` |
| 1396 | |
| 1397 | <!--- TEST --> |
| 1398 | |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1399 | ### Cancellation via explicit job |
| 1400 | |
| 1401 | Let us put our knowledge about contexts, children and jobs together. Assume that our application has |
| 1402 | an object with a lifecycle, but that object is not a coroutine. For example, we are writing an Android application |
| 1403 | and launch various coroutines in the context of an Android activity to perform asynchronous operations to fetch |
| 1404 | and update data, do animations, etc. All of these coroutines must be cancelled when activity is destroyed |
| 1405 | to avoid memory leaks. |
| 1406 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1407 | We manage a lifecycle of our coroutines by creating an instance of [Job] that is tied to |
| 1408 | the lifecycle of our activity. A job instance is created using [Job()] factory function when |
| 1409 | activity is created and it is cancelled when an activity is destroyed like this: |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1410 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1411 | <!--- INCLUDE |
| 1412 | import kotlin.coroutines.experimental.* |
| 1413 | --> |
| 1414 | |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1415 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1416 | class Activity : CoroutineScope { |
| 1417 | lateinit var job: Job |
| 1418 | |
| 1419 | fun create() { |
| 1420 | job = Job() |
| 1421 | } |
| 1422 | |
| 1423 | fun destroy() { |
| 1424 | job.cancel() |
| 1425 | } |
| 1426 | // to be continued ... |
| 1427 | ``` |
| 1428 | |
| 1429 | We also implement [CoroutineScope] interface in this `Actvity` class. We only need to provide an override |
| 1430 | for its [CoroutineScope.coroutineContext] property to specify the context for coroutines launched in its |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1431 | scope. We combine the desired dispatcher (we used [Dispatchers.Default] in this example) and a job: |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1432 | |
| 1433 | ```kotlin |
| 1434 | // class Activity continues |
| 1435 | override val coroutineContext: CoroutineContext |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1436 | get() = Dispatchers.Default + job |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1437 | // to be continued ... |
| 1438 | ``` |
| 1439 | |
| 1440 | Now, we can launch coroutines in the scope of this `Activity` without having to explicitly |
| 1441 | specify their context. For the demo, we launch ten coroutines that delay for a different time: |
| 1442 | |
| 1443 | ```kotlin |
| 1444 | // class Activity continues |
| 1445 | fun doSomething() { |
| 1446 | // launch ten coroutines for a demo, each working for a different time |
| 1447 | repeat(10) { i -> |
| 1448 | launch { |
| 1449 | delay((i + 1) * 200L) // variable delay 200ms, 400ms, ... etc |
| 1450 | println("Coroutine $i is done") |
| 1451 | } |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1452 | } |
| 1453 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1454 | } // class Activity ends |
| 1455 | ``` |
| 1456 | |
| 1457 | In our main function we create activity, call our test `doSomething` function, and destroy activity after 500ms. |
| 1458 | This cancels all the coroutines that were launched which we can confirm by noting that it does not print |
| 1459 | onto the screen anymore if we wait: |
| 1460 | |
| 1461 | |
| 1462 | ```kotlin |
| 1463 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1464 | val activity = Activity() |
| 1465 | activity.create() // create an activity |
| 1466 | activity.doSomething() // run test function |
| 1467 | println("Launched coroutines") |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1468 | delay(500L) // delay for half a second |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1469 | println("Destroying activity!") |
| 1470 | activity.destroy() // cancels all coroutines |
| 1471 | delay(1000) // visually confirm that they don't work |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1472 | } |
| 1473 | ``` |
| 1474 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1475 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-10.kt) |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1476 | |
| 1477 | The output of this example is: |
| 1478 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1479 | ```text |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1480 | Launched coroutines |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1481 | Coroutine 0 is done |
| 1482 | Coroutine 1 is done |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1483 | Destroying activity! |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1484 | ``` |
| 1485 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1486 | <!--- TEST --> |
| 1487 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1488 | As you can see, only the first two coroutines had printed a message and the others were cancelled |
| 1489 | by a single invocation of `job.cancel()` in `Activity.destroy()`. |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1490 | |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame] | 1491 | ### Thread-local data |
| 1492 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1493 | Sometimes it is convenient to have an ability to pass some thread-local data, but, for coroutines, which |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame] | 1494 | are not bound to any particular thread, it is hard to achieve it manually without writing a lot of boilerplate. |
| 1495 | |
| 1496 | For [`ThreadLocal`](https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html), |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1497 | [asContextElement] extension function is here for the rescue. It creates an additional context element, |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame] | 1498 | which keep the value of the given `ThreadLocal` and restores it every time the coroutine switches its context. |
| 1499 | |
| 1500 | It is easy to demonstrate it in action: |
| 1501 | |
| 1502 | <!--- INCLUDE |
| 1503 | import kotlin.coroutines.experimental.* |
| 1504 | --> |
| 1505 | |
| 1506 | ```kotlin |
| 1507 | val threadLocal = ThreadLocal<String?>() // declare thread-local variable |
| 1508 | |
| 1509 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1510 | threadLocal.set("main") |
| 1511 | println("Pre-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'") |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1512 | val job = launch(Dispatchers.Default + threadLocal.asContextElement(value = "launch")) { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1513 | println("Launch start, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'") |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame] | 1514 | yield() |
| 1515 | println("After yield, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'") |
| 1516 | } |
| 1517 | job.join() |
| 1518 | println("Post-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'") |
| 1519 | } |
| 1520 | ``` |
| 1521 | |
| 1522 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-11.kt) |
| 1523 | |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 1524 | In this example we launch new coroutine in a background thread pool using [Dispatchers.Default], so |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1525 | it works on a different threads from a thread pool, but it still has the value of thread local variable, |
| 1526 | that we've specified using `threadLocal.asContextElement(value = "launch")`, |
| 1527 | no matter on what thread the coroutine is executed. |
| 1528 | Thus, output (with [debug](#debugging-coroutines-and-threads)) is: |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame] | 1529 | |
| 1530 | ```text |
| 1531 | Pre-main, current thread: Thread[main @coroutine#1,5,main], thread local value: 'main' |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1532 | Launch start, current thread: Thread[CommonPool-worker-1 @coroutine#2,5,main], thread local value: 'launch' |
| 1533 | After yield, current thread: Thread[CommonPool-worker-2 @coroutine#2,5,main], thread local value: 'launch' |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame] | 1534 | Post-main, current thread: Thread[main @coroutine#1,5,main], thread local value: 'main' |
| 1535 | ``` |
| 1536 | |
| 1537 | <!--- TEST FLEXIBLE_THREAD --> |
| 1538 | |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame] | 1539 | `ThreadLocal` has first-class support and can be used with any primitive `kotlinx.corotuines` provides. |
| 1540 | It has one key limitation: when thread-local is mutated, a new value is not propagated to the coroutine caller |
| 1541 | (as context element cannot track all `ThreadLocal` object accesses) and updated value is lost on the next suspension. |
| 1542 | Use [withContext] to update the value of the thread-local in a coroutine, see [asContextElement] for more details. |
| 1543 | |
| 1544 | Alternatively, a value can be stored in a mutable box like `class Counter(var i: Int)`, which is, in turn, |
| 1545 | is stored in a thread-local variable. However, in this case you are fully responsible to synchronize |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1546 | potentially concurrent modifications to the variable in this mutable box. |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame] | 1547 | |
| 1548 | For advanced usage, for example for integration with logging MDC, transactional contexts or any other libraries |
| 1549 | which internally use thread-locals for passing data, see documentation for [ThreadContextElement] interface |
| 1550 | that should be implemented. |
| 1551 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1552 | ## Exception handling |
| 1553 | |
| 1554 | <!--- INCLUDE .*/example-exceptions-([0-9]+).kt |
| 1555 | --> |
| 1556 | |
| 1557 | This section covers exception handling and cancellation on exceptions. |
| 1558 | We already know that cancelled coroutine throws [CancellationException] in suspension points and that it |
| 1559 | is ignored by coroutines machinery. But what happens if an exception is thrown during cancellation or multiple children of the same |
| 1560 | coroutine throw an exception? |
| 1561 | |
| 1562 | ### Exception propagation |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1563 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1564 | Coroutine builders come in two flavors: propagating exceptions automatically ([launch] and [actor]) or |
| 1565 | exposing them to users ([async] and [produce]). |
| 1566 | The former treat exceptions as unhandled, similar to Java's `Thread.uncaughExceptionHandler`, |
| 1567 | while the latter are relying on the user to consume the final |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1568 | exception, for example via [await][Deferred.await] or [receive][ReceiveChannel.receive] |
| 1569 | ([produce] and [receive][ReceiveChannel.receive] are covered later in [Channels](#channels) section). |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1570 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1571 | It can be demonstrated by a simple example that creates new coroutines in [GlobalScope]: |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1572 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1573 | ```kotlin |
| 1574 | fun main(args: Array<String>) = runBlocking { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1575 | val job = GlobalScope.launch { |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1576 | println("Throwing exception from launch") |
| 1577 | throw IndexOutOfBoundsException() // Will be printed to the console by Thread.defaultUncaughtExceptionHandler |
| 1578 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1579 | job.join() |
| 1580 | println("Joined failed job") |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1581 | val deferred = GlobalScope.async { |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1582 | println("Throwing exception from async") |
| 1583 | throw ArithmeticException() // Nothing is printed, relying on user to call await |
| 1584 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1585 | try { |
| 1586 | deferred.await() |
| 1587 | println("Unreached") |
| 1588 | } catch (e: ArithmeticException) { |
| 1589 | println("Caught ArithmeticException") |
| 1590 | } |
| 1591 | } |
| 1592 | ``` |
| 1593 | |
| 1594 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-01.kt) |
| 1595 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1596 | The output of this code is (with [debug](#debugging-coroutines-and-threads)): |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1597 | |
| 1598 | ```text |
| 1599 | Throwing exception from launch |
| 1600 | Exception in thread "ForkJoinPool.commonPool-worker-2 @coroutine#2" java.lang.IndexOutOfBoundsException |
| 1601 | Joined failed job |
| 1602 | Throwing exception from async |
| 1603 | Caught ArithmeticException |
| 1604 | ``` |
| 1605 | |
| 1606 | <!--- TEST EXCEPTION--> |
| 1607 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1608 | ### CoroutineExceptionHandler |
| 1609 | |
| 1610 | But what if one does not want to print all exceptions to the console? |
| 1611 | [CoroutineExceptionHandler] context element is used as generic `catch` block of coroutine where custom logging or exception handling may take place. |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1612 | It is similar to using [`Thread.uncaughtExceptionHandler`](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)). |
| 1613 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1614 | On JVM it is possible to redefine global exception handler for all coroutines by registering [CoroutineExceptionHandler] via |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1615 | [`ServiceLoader`](https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html). |
| 1616 | Global exception handler is similar to |
| 1617 | [`Thread.defaultUncaughtExceptionHandler`](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)) |
| 1618 | which is used when no more specific handlers are registered. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1619 | On Android, `uncaughtExceptionPreHandler` is installed as a global coroutine exception handler. |
| 1620 | |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1621 | [CoroutineExceptionHandler] is invoked only on exceptions which are not expected to be handled by the user, |
| 1622 | so registering it in [async] builder and the like of it has no effect. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1623 | |
| 1624 | ```kotlin |
| 1625 | fun main(args: Array<String>) = runBlocking { |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1626 | val handler = CoroutineExceptionHandler { _, exception -> |
| 1627 | println("Caught $exception") |
| 1628 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1629 | val job = GlobalScope.launch(handler) { |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1630 | throw AssertionError() |
| 1631 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1632 | val deferred = GlobalScope.async(handler) { |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1633 | throw ArithmeticException() // Nothing will be printed, relying on user to call deferred.await() |
| 1634 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1635 | joinAll(job, deferred) |
| 1636 | } |
| 1637 | ``` |
| 1638 | |
| 1639 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-02.kt) |
| 1640 | |
| 1641 | The output of this code is: |
| 1642 | |
| 1643 | ```text |
| 1644 | Caught java.lang.AssertionError |
| 1645 | ``` |
| 1646 | |
| 1647 | <!--- TEST--> |
| 1648 | |
| 1649 | ### Cancellation and exceptions |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1650 | |
| 1651 | Cancellation is tightly bound with exceptions. Coroutines internally use `CancellationException` for cancellation, these |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1652 | exceptions are ignored by all handlers, so they should be used only as the source of additional debug information, which can |
| 1653 | be obtained by `catch` block. |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1654 | When a coroutine is cancelled using [Job.cancel] without a cause, it terminates, but it does not cancel its parent. |
| 1655 | Cancelling without cause is a mechanism for parent to cancel its children without cancelling itself. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1656 | |
| 1657 | <!--- INCLUDE |
| 1658 | import kotlin.coroutines.experimental.* |
| 1659 | --> |
| 1660 | |
| 1661 | ```kotlin |
| 1662 | fun main(args: Array<String>) = runBlocking { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1663 | val job = launch { |
| 1664 | val child = launch { |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1665 | try { |
| 1666 | delay(Long.MAX_VALUE) |
| 1667 | } finally { |
| 1668 | println("Child is cancelled") |
| 1669 | } |
| 1670 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1671 | yield() |
| 1672 | println("Cancelling child") |
| 1673 | child.cancel() |
| 1674 | child.join() |
| 1675 | yield() |
| 1676 | println("Parent is not cancelled") |
| 1677 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1678 | job.join() |
| 1679 | } |
| 1680 | ``` |
| 1681 | |
| 1682 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-03.kt) |
| 1683 | |
| 1684 | The output of this code is: |
| 1685 | |
| 1686 | ```text |
| 1687 | Cancelling child |
| 1688 | Child is cancelled |
| 1689 | Parent is not cancelled |
| 1690 | ``` |
| 1691 | |
| 1692 | <!--- TEST--> |
| 1693 | |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1694 | If a coroutine encounters exception other than `CancellationException`, it cancels its parent with that exception. |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1695 | This behaviour cannot be overridden and is used to provide stable coroutines hierarchies for |
| 1696 | [structured concurrency](#structured-concurrency) which do not depend on |
| 1697 | [CoroutineExceptionHandler] implementation. |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1698 | The original exception is handled by the parent when all its children terminate. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1699 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1700 | > This also a reason why, in these examples, [CoroutineExceptionHandler] is always installed to a coroutine |
| 1701 | that is created in [GlobalScope]. It does not make sense to install an exception handler to a coroutine that |
| 1702 | is launched in the scope of the main [runBlocking], since the main coroutine is going to be always cancelled |
| 1703 | when its child completes with exception despite the installed handler. |
| 1704 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1705 | <!--- INCLUDE |
| 1706 | import kotlin.coroutines.experimental.* |
| 1707 | --> |
| 1708 | |
| 1709 | ```kotlin |
| 1710 | fun main(args: Array<String>) = runBlocking { |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1711 | val handler = CoroutineExceptionHandler { _, exception -> |
| 1712 | println("Caught $exception") |
| 1713 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1714 | val job = GlobalScope.launch(handler) { |
| 1715 | launch { // the first child |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1716 | try { |
| 1717 | delay(Long.MAX_VALUE) |
| 1718 | } finally { |
| 1719 | withContext(NonCancellable) { |
| 1720 | println("Children are cancelled, but exception is not handled until all children terminate") |
| 1721 | delay(100) |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1722 | println("The first child finished its non cancellable block") |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1723 | } |
| 1724 | } |
| 1725 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1726 | launch { // the second child |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1727 | delay(10) |
| 1728 | println("Second child throws an exception") |
| 1729 | throw ArithmeticException() |
| 1730 | } |
| 1731 | } |
| 1732 | job.join() |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1733 | } |
| 1734 | ``` |
| 1735 | |
| 1736 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-04.kt) |
| 1737 | |
| 1738 | The output of this code is: |
| 1739 | |
| 1740 | ```text |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1741 | Second child throws an exception |
| 1742 | Children are cancelled, but exception is not handled until all children terminate |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1743 | The first child finished its non cancellable block |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1744 | Caught java.lang.ArithmeticException |
| 1745 | ``` |
| 1746 | <!--- TEST--> |
| 1747 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1748 | ### Exceptions aggregation |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1749 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1750 | What happens if multiple children of a coroutine throw an exception? |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1751 | The general rule is "the first exception wins", so the first thrown exception is exposed to the handler. |
| 1752 | But that may cause lost exceptions, for example if coroutine throws an exception in its `finally` block. |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1753 | So, additional exceptions are suppressed. |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1754 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1755 | > One of the solutions would have been to report each exception separately, |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1756 | but then [Deferred.await] should have had the same mechanism to avoid behavioural inconsistency and this |
| 1757 | would cause implementation details of a coroutines (whether it had delegate parts of its work to its children or not) |
| 1758 | to leak to its exception handler. |
| 1759 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1760 | <!--- INCLUDE |
| 1761 | import kotlinx.coroutines.experimental.exceptions.* |
| 1762 | import kotlin.coroutines.experimental.* |
| 1763 | import java.io.* |
| 1764 | --> |
| 1765 | |
| 1766 | ```kotlin |
| 1767 | fun main(args: Array<String>) = runBlocking { |
| 1768 | val handler = CoroutineExceptionHandler { _, exception -> |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1769 | println("Caught $exception with suppressed ${exception.suppressed().contentToString()}") |
| 1770 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1771 | val job = GlobalScope.launch(handler) { |
| 1772 | launch { |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1773 | try { |
| 1774 | delay(Long.MAX_VALUE) |
| 1775 | } finally { |
| 1776 | throw ArithmeticException() |
| 1777 | } |
| 1778 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1779 | launch { |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1780 | throw IOException() |
| 1781 | } |
| 1782 | delay(Long.MAX_VALUE) |
| 1783 | } |
| 1784 | job.join() |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1785 | } |
| 1786 | ``` |
| 1787 | |
| 1788 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-05.kt) |
| 1789 | |
| 1790 | The output of this code is: |
| 1791 | |
| 1792 | ```text |
| 1793 | Caught java.io.IOException with suppressed [java.lang.ArithmeticException] |
| 1794 | ``` |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1795 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1796 | <!--- TEST--> |
| 1797 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1798 | > Note, this mechanism currently works only on Java version 1.7+. |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1799 | Limitation on JS and Native is temporary and will be fixed in the future. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1800 | |
| 1801 | Cancellation exceptions are transparent and unwrapped by default: |
| 1802 | |
| 1803 | <!--- INCLUDE |
| 1804 | import kotlin.coroutines.experimental.* |
| 1805 | import java.io.* |
| 1806 | --> |
| 1807 | |
| 1808 | ```kotlin |
| 1809 | fun main(args: Array<String>) = runBlocking { |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1810 | val handler = CoroutineExceptionHandler { _, exception -> |
| 1811 | println("Caught original $exception") |
| 1812 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1813 | val job = GlobalScope.launch(handler) { |
| 1814 | val inner = launch { |
| 1815 | launch { |
| 1816 | launch { |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1817 | throw IOException() |
| 1818 | } |
| 1819 | } |
| 1820 | } |
| 1821 | try { |
| 1822 | inner.join() |
| 1823 | } catch (e: JobCancellationException) { |
| 1824 | println("Rethrowing JobCancellationException with original cause") |
| 1825 | throw e |
| 1826 | } |
| 1827 | } |
| 1828 | job.join() |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1829 | } |
| 1830 | ``` |
| 1831 | |
| 1832 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-06.kt) |
| 1833 | |
| 1834 | The output of this code is: |
| 1835 | |
| 1836 | ```text |
| 1837 | Rethrowing JobCancellationException with original cause |
| 1838 | Caught original java.io.IOException |
| 1839 | ``` |
| 1840 | <!--- TEST--> |
| 1841 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1842 | ## Channels (experimental) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 1843 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1844 | Deferred values provide a convenient way to transfer a single value between coroutines. |
| 1845 | Channels provide a way to transfer a stream of values. |
| 1846 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1847 | > Channels are an experimental feature of `kotlinx.coroutines`. Their API is expected to |
| 1848 | evolve in the upcoming updates of the `kotlinx.coroutines` library with potentially |
| 1849 | breaking changes. |
| 1850 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1851 | <!--- INCLUDE .*/example-channel-([0-9]+).kt |
| 1852 | import kotlinx.coroutines.experimental.channels.* |
| 1853 | --> |
| 1854 | |
| 1855 | ### Channel basics |
| 1856 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1857 | A [Channel] is conceptually very similar to `BlockingQueue`. One key difference is that |
| 1858 | instead of a blocking `put` operation it has a suspending [send][SendChannel.send], and instead of |
| 1859 | a blocking `take` operation it has a suspending [receive][ReceiveChannel.receive]. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1860 | |
| 1861 | ```kotlin |
| 1862 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1863 | val channel = Channel<Int>() |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1864 | launch { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1865 | // this might be heavy CPU-consuming computation or async logic, we'll just send five squares |
| 1866 | for (x in 1..5) channel.send(x * x) |
| 1867 | } |
| 1868 | // here we print five received integers: |
| 1869 | repeat(5) { println(channel.receive()) } |
| 1870 | println("Done!") |
| 1871 | } |
| 1872 | ``` |
| 1873 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1874 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-01.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1875 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1876 | The output of this code is: |
| 1877 | |
| 1878 | ```text |
| 1879 | 1 |
| 1880 | 4 |
| 1881 | 9 |
| 1882 | 16 |
| 1883 | 25 |
| 1884 | Done! |
| 1885 | ``` |
| 1886 | |
| 1887 | <!--- TEST --> |
| 1888 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1889 | ### Closing and iteration over channels |
| 1890 | |
| 1891 | Unlike a queue, a channel can be closed to indicate that no more elements are coming. |
| 1892 | On the receiver side it is convenient to use a regular `for` loop to receive elements |
| 1893 | from the channel. |
| 1894 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1895 | 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] | 1896 | The iteration stops as soon as this close token is received, so there is a guarantee |
| 1897 | that all previously sent elements before the close are received: |
| 1898 | |
| 1899 | ```kotlin |
| 1900 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1901 | val channel = Channel<Int>() |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1902 | launch { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1903 | for (x in 1..5) channel.send(x * x) |
| 1904 | channel.close() // we're done sending |
| 1905 | } |
| 1906 | // here we print received values using `for` loop (until the channel is closed) |
| 1907 | for (y in channel) println(y) |
| 1908 | println("Done!") |
| 1909 | } |
| 1910 | ``` |
| 1911 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1912 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-02.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1913 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1914 | <!--- TEST |
| 1915 | 1 |
| 1916 | 4 |
| 1917 | 9 |
| 1918 | 16 |
| 1919 | 25 |
| 1920 | Done! |
| 1921 | --> |
| 1922 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1923 | ### Building channel producers |
| 1924 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1925 | The pattern where a coroutine is producing a sequence of elements is quite common. |
| 1926 | 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] | 1927 | 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] | 1928 | to common sense that results must be returned from functions. |
| 1929 | |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 1930 | There is a convenience coroutine builder named [produce] that makes it easy to do it right on producer side, |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1931 | and an extension function [consumeEach], that replaces a `for` loop on the consumer side: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1932 | |
| 1933 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1934 | fun CoroutineScope.produceSquares() = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1935 | for (x in 1..5) send(x * x) |
| 1936 | } |
| 1937 | |
| 1938 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1939 | val squares = produceSquares() |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 1940 | squares.consumeEach { println(it) } |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1941 | println("Done!") |
| 1942 | } |
| 1943 | ``` |
| 1944 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1945 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-03.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1946 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1947 | <!--- TEST |
| 1948 | 1 |
| 1949 | 4 |
| 1950 | 9 |
| 1951 | 16 |
| 1952 | 25 |
| 1953 | Done! |
| 1954 | --> |
| 1955 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1956 | ### Pipelines |
| 1957 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1958 | A pipeline is a pattern where one coroutine is producing, possibly infinite, stream of values: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1959 | |
| 1960 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1961 | fun CoroutineScope.produceNumbers() = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1962 | var x = 1 |
| 1963 | while (true) send(x++) // infinite stream of integers starting from 1 |
| 1964 | } |
| 1965 | ``` |
| 1966 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1967 | 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] | 1968 | In the below example the numbers are just squared: |
| 1969 | |
| 1970 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1971 | fun CoroutineScope.square(numbers: ReceiveChannel<Int>) = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1972 | for (x in numbers) send(x * x) |
| 1973 | } |
| 1974 | ``` |
| 1975 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1976 | The main code starts and connects the whole pipeline: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1977 | |
| 1978 | ```kotlin |
| 1979 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1980 | val numbers = produceNumbers() // produces integers from 1 and on |
| 1981 | val squares = square(numbers) // squares integers |
| 1982 | for (i in 1..5) println(squares.receive()) // print first five |
| 1983 | println("Done!") // we are done |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1984 | coroutineContext.cancelChildren() // cancel children coroutines |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1985 | } |
| 1986 | ``` |
| 1987 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1988 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-04.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1989 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1990 | <!--- TEST |
| 1991 | 1 |
| 1992 | 4 |
| 1993 | 9 |
| 1994 | 16 |
| 1995 | 25 |
| 1996 | Done! |
| 1997 | --> |
| 1998 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 1999 | > All functions that create coroutines are defined as extensions on [CoroutineScope], |
| 2000 | so that we can rely on [structured concurrency](#structured-concurrency) to make |
| 2001 | sure that we don't have lingering global coroutines in our application. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2002 | |
| 2003 | ### Prime numbers with pipeline |
| 2004 | |
Cedric Beust | fa0b28f | 2017-02-07 07:07:25 -0800 | [diff] [blame] | 2005 | Let's take pipelines to the extreme with an example that generates prime numbers using a pipeline |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2006 | of coroutines. We start with an infinite sequence of numbers. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2007 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2008 | <!--- INCLUDE |
| 2009 | import kotlin.coroutines.experimental.* |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2010 | --> |
| 2011 | |
| 2012 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2013 | fun CoroutineScope.numbersFrom(start: Int) = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2014 | var x = start |
| 2015 | while (true) send(x++) // infinite stream of integers from start |
| 2016 | } |
| 2017 | ``` |
| 2018 | |
| 2019 | The following pipeline stage filters an incoming stream of numbers, removing all the numbers |
| 2020 | that are divisible by the given prime number: |
| 2021 | |
| 2022 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2023 | fun CoroutineScope.filter(numbers: ReceiveChannel<Int>, prime: Int) = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2024 | for (x in numbers) if (x % prime != 0) send(x) |
| 2025 | } |
| 2026 | ``` |
| 2027 | |
| 2028 | 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] | 2029 | and launching new pipeline stage for each prime number found: |
| 2030 | |
| 2031 | ``` |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 2032 | numbersFrom(2) -> filter(2) -> filter(3) -> filter(5) -> filter(7) ... |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 2033 | ``` |
| 2034 | |
| 2035 | The following example prints the first ten prime numbers, |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2036 | running the whole pipeline in the context of the main thread. Since all the coroutines are launched in |
| 2037 | the scope of the main [runBlocking] coroutine |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2038 | we don't have to keep an explicit list of all the coroutines we have started. |
Roman Elizarov | 3e387b8 | 2017-12-04 13:49:11 +0300 | [diff] [blame] | 2039 | We use [cancelChildren][kotlin.coroutines.experimental.CoroutineContext.cancelChildren] |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2040 | extension function to cancel all the children coroutines after we have printed |
| 2041 | the first ten prime numbers. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2042 | |
| 2043 | ```kotlin |
| 2044 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2045 | var cur = numbersFrom(2) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2046 | for (i in 1..10) { |
| 2047 | val prime = cur.receive() |
| 2048 | println(prime) |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2049 | cur = filter(cur, prime) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2050 | } |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2051 | coroutineContext.cancelChildren() // cancel all children to let main finish |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2052 | } |
| 2053 | ``` |
| 2054 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2055 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-05.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2056 | |
| 2057 | The output of this code is: |
| 2058 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2059 | ```text |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2060 | 2 |
| 2061 | 3 |
| 2062 | 5 |
| 2063 | 7 |
| 2064 | 11 |
| 2065 | 13 |
| 2066 | 17 |
| 2067 | 19 |
| 2068 | 23 |
| 2069 | 29 |
| 2070 | ``` |
| 2071 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2072 | <!--- TEST --> |
| 2073 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 2074 | Note, that you can build the same pipeline using |
| 2075 | [`buildIterator`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/build-iterator.html) |
| 2076 | coroutine builder from the standard library. |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 2077 | Replace `produce` with `buildIterator`, `send` with `yield`, `receive` with `next`, |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2078 | `ReceiveChannel` with `Iterator`, and get rid of the coroutine scope. You will not need `runBlocking` either. |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 2079 | However, the benefit of a pipeline that uses channels as shown above is that it can actually use |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 2080 | multiple CPU cores if you run it in [Dispatchers.Default] context. |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 2081 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 2082 | 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] | 2083 | other suspending invocations (like asynchronous calls to remote services) and these pipelines cannot be |
SashaKhyzhun | cb2998b | 2018-07-31 11:51:35 +0300 | [diff] [blame] | 2084 | built using `buildSequence`/`buildIterator`, because they do not allow arbitrary suspension, unlike |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 2085 | `produce`, which is fully asynchronous. |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 2086 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2087 | ### Fan-out |
| 2088 | |
| 2089 | Multiple coroutines may receive from the same channel, distributing work between themselves. |
| 2090 | Let us start with a producer coroutine that is periodically producing integers |
| 2091 | (ten numbers per second): |
| 2092 | |
| 2093 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2094 | fun CoroutineScope.produceNumbers() = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2095 | var x = 1 // start from 1 |
| 2096 | while (true) { |
| 2097 | send(x++) // produce next |
| 2098 | delay(100) // wait 0.1s |
| 2099 | } |
| 2100 | } |
| 2101 | ``` |
| 2102 | |
| 2103 | Then we can have several processor coroutines. In this example, they just print their id and |
| 2104 | received number: |
| 2105 | |
| 2106 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2107 | fun CoroutineScope.launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch { |
bill | 58c61c7 | 2018-06-21 17:24:08 -0500 | [diff] [blame] | 2108 | for (msg in channel) { |
| 2109 | println("Processor #$id received $msg") |
Roman Elizarov | ec9384c | 2017-03-02 22:09:08 +0300 | [diff] [blame] | 2110 | } |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2111 | } |
| 2112 | ``` |
| 2113 | |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 2114 | 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] | 2115 | |
| 2116 | ```kotlin |
| 2117 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2118 | val producer = produceNumbers() |
| 2119 | repeat(5) { launchProcessor(it, producer) } |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 2120 | delay(950) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2121 | producer.cancel() // cancel producer coroutine and thus kill them all |
| 2122 | } |
| 2123 | ``` |
| 2124 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2125 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-06.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2126 | |
| 2127 | The output will be similar to the the following one, albeit the processor ids that receive |
| 2128 | each specific integer may be different: |
| 2129 | |
| 2130 | ``` |
| 2131 | Processor #2 received 1 |
| 2132 | Processor #4 received 2 |
| 2133 | Processor #0 received 3 |
| 2134 | Processor #1 received 4 |
| 2135 | Processor #3 received 5 |
| 2136 | Processor #2 received 6 |
| 2137 | Processor #4 received 7 |
| 2138 | Processor #0 received 8 |
| 2139 | Processor #1 received 9 |
| 2140 | Processor #3 received 10 |
| 2141 | ``` |
| 2142 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2143 | <!--- TEST lines.size == 10 && lines.withIndex().all { (i, line) -> line.startsWith("Processor #") && line.endsWith(" received ${i + 1}") } --> |
| 2144 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2145 | Note, that cancelling a producer coroutine closes its channel, thus eventually terminating iteration |
| 2146 | over the channel that processor coroutines are doing. |
| 2147 | |
Roman Elizarov | 1ce6c0b | 2018-06-28 10:37:20 +0300 | [diff] [blame] | 2148 | Also, pay attention to how we explicitly iterate over channel with `for` loop to perform fan-out in `launchProcessor` code. |
| 2149 | Unlike `consumeEach`, this `for` loop pattern is perfectly safe to use from multiple coroutines. If one of the processor |
| 2150 | coroutines fails, then others would still be processing the channel, while a processor that is written via `consumeEach` |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2151 | always consumes (cancels) the underlying channel on its normal or abnormal completion. |
Roman Elizarov | 1ce6c0b | 2018-06-28 10:37:20 +0300 | [diff] [blame] | 2152 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2153 | ### Fan-in |
| 2154 | |
| 2155 | Multiple coroutines may send to the same channel. |
| 2156 | For example, let us have a channel of strings, and a suspending function that |
| 2157 | repeatedly sends a specified string to this channel with a specified delay: |
| 2158 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2159 | <!--- INCLUDE |
| 2160 | import kotlin.coroutines.experimental.* |
| 2161 | --> |
| 2162 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2163 | ```kotlin |
| 2164 | suspend fun sendString(channel: SendChannel<String>, s: String, time: Long) { |
| 2165 | while (true) { |
| 2166 | delay(time) |
| 2167 | channel.send(s) |
| 2168 | } |
| 2169 | } |
| 2170 | ``` |
| 2171 | |
Cedric Beust | fa0b28f | 2017-02-07 07:07:25 -0800 | [diff] [blame] | 2172 | Now, let us see what happens if we launch a couple of coroutines sending strings |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2173 | (in this example we launch them in the context of the main thread as main coroutine's children): |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2174 | |
| 2175 | ```kotlin |
| 2176 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2177 | val channel = Channel<String>() |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2178 | launch { sendString(channel, "foo", 200L) } |
| 2179 | launch { sendString(channel, "BAR!", 500L) } |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2180 | repeat(6) { // receive first six |
| 2181 | println(channel.receive()) |
| 2182 | } |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2183 | coroutineContext.cancelChildren() // cancel all children to let main finish |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2184 | } |
| 2185 | ``` |
| 2186 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2187 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-07.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2188 | |
| 2189 | The output is: |
| 2190 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2191 | ```text |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2192 | foo |
| 2193 | foo |
| 2194 | BAR! |
| 2195 | foo |
| 2196 | foo |
| 2197 | BAR! |
| 2198 | ``` |
| 2199 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2200 | <!--- TEST --> |
| 2201 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2202 | ### Buffered channels |
| 2203 | |
| 2204 | The channels shown so far had no buffer. Unbuffered channels transfer elements when sender and receiver |
| 2205 | meet each other (aka rendezvous). If send is invoked first, then it is suspended until receive is invoked, |
| 2206 | if receive is invoked first, it is suspended until send is invoked. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2207 | |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 2208 | Both [Channel()] factory function and [produce] builder take an optional `capacity` parameter to |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2209 | specify _buffer size_. Buffer allows senders to send multiple elements before suspending, |
| 2210 | similar to the `BlockingQueue` with a specified capacity, which blocks when buffer is full. |
| 2211 | |
| 2212 | Take a look at the behavior of the following code: |
| 2213 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2214 | <!--- INCLUDE |
| 2215 | import kotlin.coroutines.experimental.* |
| 2216 | --> |
| 2217 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2218 | ```kotlin |
| 2219 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2220 | val channel = Channel<Int>(4) // create buffered channel |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2221 | val sender = launch { // launch sender coroutine |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2222 | repeat(10) { |
| 2223 | println("Sending $it") // print before sending each element |
| 2224 | channel.send(it) // will suspend when buffer is full |
| 2225 | } |
| 2226 | } |
| 2227 | // don't receive anything... just wait.... |
| 2228 | delay(1000) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2229 | sender.cancel() // cancel sender coroutine |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2230 | } |
| 2231 | ``` |
| 2232 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2233 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-08.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2234 | |
| 2235 | It prints "sending" _five_ times using a buffered channel with capacity of _four_: |
| 2236 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2237 | ```text |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2238 | Sending 0 |
| 2239 | Sending 1 |
| 2240 | Sending 2 |
| 2241 | Sending 3 |
| 2242 | Sending 4 |
| 2243 | ``` |
| 2244 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2245 | <!--- TEST --> |
| 2246 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2247 | 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] | 2248 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2249 | ### Channels are fair |
| 2250 | |
| 2251 | Send and receive operations to channels are _fair_ with respect to the order of their invocation from |
| 2252 | multiple coroutines. They are served in first-in first-out order, e.g. the first coroutine to invoke `receive` |
| 2253 | gets the element. In the following example two coroutines "ping" and "pong" are |
| 2254 | receiving the "ball" object from the shared "table" channel. |
| 2255 | |
| 2256 | <!--- INCLUDE |
| 2257 | import kotlin.coroutines.experimental.* |
| 2258 | --> |
| 2259 | |
| 2260 | ```kotlin |
| 2261 | data class Ball(var hits: Int) |
| 2262 | |
| 2263 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2264 | val table = Channel<Ball>() // a shared table |
| 2265 | launch { player("ping", table) } |
| 2266 | launch { player("pong", table) } |
| 2267 | table.send(Ball(0)) // serve the ball |
| 2268 | delay(1000) // delay 1 second |
| 2269 | coroutineContext.cancelChildren() // game over, cancel them |
| 2270 | } |
| 2271 | |
| 2272 | suspend fun player(name: String, table: Channel<Ball>) { |
| 2273 | for (ball in table) { // receive the ball in a loop |
| 2274 | ball.hits++ |
| 2275 | println("$name $ball") |
| 2276 | delay(300) // wait a bit |
| 2277 | table.send(ball) // send the ball back |
| 2278 | } |
| 2279 | } |
| 2280 | ``` |
| 2281 | |
| 2282 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-09.kt) |
| 2283 | |
| 2284 | The "ping" coroutine is started first, so it is the first one to receive the ball. Even though "ping" |
| 2285 | coroutine immediately starts receiving the ball again after sending it back to the table, the ball gets |
| 2286 | received by the "pong" coroutine, because it was already waiting for it: |
| 2287 | |
| 2288 | ```text |
| 2289 | ping Ball(hits=1) |
| 2290 | pong Ball(hits=2) |
| 2291 | ping Ball(hits=3) |
| 2292 | pong Ball(hits=4) |
| 2293 | ``` |
| 2294 | |
| 2295 | <!--- TEST --> |
| 2296 | |
| 2297 | Note, that sometimes channels may produce executions that look unfair due to the nature of the executor |
| 2298 | that is being used. See [this issue](https://github.com/Kotlin/kotlinx.coroutines/issues/111) for details. |
| 2299 | |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 2300 | ### Ticker channels |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2301 | |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2302 | Ticker channel is a special rendezvous channel that produces `Unit` every time given delay passes since last consumption from this channel. |
| 2303 | Though it may seem to be useless standalone, it is a useful building block to create complex time-based [produce] |
Roman Elizarov | 0c090ed | 2018-06-29 19:51:07 +0300 | [diff] [blame] | 2304 | pipelines and operators that do windowing and other time-dependent processing. |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2305 | Ticker channel can be used in [select] to perform "on tick" action. |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2306 | |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2307 | To create such channel use a factory method [ticker]. |
| 2308 | To indicate that no further elements are needed use [ReceiveChannel.cancel] method on it. |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2309 | |
| 2310 | Now let's see how it works in practice: |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2311 | |
| 2312 | ```kotlin |
| 2313 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2314 | val tickerChannel = ticker(delay = 100, initialDelay = 0) // create ticker channel |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 2315 | var nextElement = withTimeoutOrNull(1) { tickerChannel.receive() } |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2316 | println("Initial element is available immediately: $nextElement") // initial delay hasn't passed yet |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2317 | |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2318 | nextElement = withTimeoutOrNull(50) { tickerChannel.receive() } // all subsequent elements has 100ms delay |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2319 | println("Next element is not ready in 50 ms: $nextElement") |
| 2320 | |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2321 | nextElement = withTimeoutOrNull(60) { tickerChannel.receive() } |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2322 | println("Next element is ready in 100 ms: $nextElement") |
| 2323 | |
| 2324 | // Emulate large consumption delays |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2325 | println("Consumer pauses for 150ms") |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2326 | delay(150) |
| 2327 | // Next element is available immediately |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 2328 | nextElement = withTimeoutOrNull(1) { tickerChannel.receive() } |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2329 | println("Next element is available immediately after large consumer delay: $nextElement") |
| 2330 | // Note that the pause between `receive` calls is taken into account and next element arrives faster |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2331 | nextElement = withTimeoutOrNull(60) { tickerChannel.receive() } |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2332 | println("Next element is ready in 50ms after consumer pause in 150ms: $nextElement") |
| 2333 | |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 2334 | tickerChannel.cancel() // indicate that no more elements are needed |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2335 | } |
| 2336 | ``` |
| 2337 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2338 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-10.kt) |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2339 | |
| 2340 | It prints following lines: |
| 2341 | |
| 2342 | ```text |
| 2343 | Initial element is available immediately: kotlin.Unit |
| 2344 | Next element is not ready in 50 ms: null |
| 2345 | Next element is ready in 100 ms: kotlin.Unit |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2346 | Consumer pauses for 150ms |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2347 | Next element is available immediately after large consumer delay: kotlin.Unit |
| 2348 | Next element is ready in 50ms after consumer pause in 150ms: kotlin.Unit |
| 2349 | ``` |
| 2350 | |
| 2351 | <!--- TEST --> |
| 2352 | |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2353 | Note that [ticker] is aware of possible consumer pauses and, by default, adjusts next produced element |
| 2354 | delay if a pause occurs, trying to maintain a fixed rate of produced elements. |
| 2355 | |
Roman Elizarov | 0c090ed | 2018-06-29 19:51:07 +0300 | [diff] [blame] | 2356 | Optionally, a `mode` parameter equal to [TickerMode.FIXED_DELAY] can be specified to maintain a fixed |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2357 | delay between elements. |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2358 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2359 | ## Shared mutable state and concurrency |
| 2360 | |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 2361 | Coroutines can be executed concurrently using a multi-threaded dispatcher like the [Dispatchers.Default]. It presents |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2362 | all the usual concurrency problems. The main problem being synchronization of access to **shared mutable state**. |
| 2363 | Some solutions to this problem in the land of coroutines are similar to the solutions in the multi-threaded world, |
| 2364 | but others are unique. |
| 2365 | |
| 2366 | ### The problem |
| 2367 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2368 | Let us launch a hundred coroutines all doing the same action thousand times. |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2369 | We'll also measure their completion time for further comparisons: |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2370 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2371 | <!--- INCLUDE .*/example-sync-03.kt |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2372 | import java.util.concurrent.atomic.* |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2373 | --> |
| 2374 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2375 | <!--- INCLUDE .*/example-sync-06.kt |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2376 | import kotlinx.coroutines.experimental.sync.* |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2377 | --> |
| 2378 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2379 | <!--- INCLUDE .*/example-sync-07.kt |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2380 | import kotlinx.coroutines.experimental.channels.* |
| 2381 | --> |
| 2382 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2383 | <!--- INCLUDE .*/example-sync-([0-9a-z]+).kt |
| 2384 | import kotlin.system.* |
| 2385 | import kotlin.coroutines.experimental.* |
| 2386 | --> |
| 2387 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2388 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2389 | suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { |
| 2390 | val n = 100 // number of coroutines to launch |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2391 | val k = 1000 // times an action is repeated by each coroutine |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2392 | val time = measureTimeMillis { |
| 2393 | val jobs = List(n) { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2394 | launch { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2395 | repeat(k) { action() } |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2396 | } |
| 2397 | } |
| 2398 | jobs.forEach { it.join() } |
| 2399 | } |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2400 | println("Completed ${n * k} actions in $time ms") |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2401 | } |
| 2402 | ``` |
| 2403 | |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 2404 | <!--- INCLUDE .*/example-sync-([0-9a-z]+).kt --> |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2405 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2406 | We start with a very simple action that increments a shared mutable variable using |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 2407 | multi-threaded [Dispatchers.Default] that is used in [GlobalScope]. |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2408 | |
| 2409 | ```kotlin |
| 2410 | var counter = 0 |
| 2411 | |
| 2412 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2413 | GlobalScope.massiveRun { |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2414 | counter++ |
| 2415 | } |
| 2416 | println("Counter = $counter") |
| 2417 | } |
| 2418 | ``` |
| 2419 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2420 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-01.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2421 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2422 | <!--- TEST LINES_START |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2423 | Completed 100000 actions in |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2424 | Counter = |
| 2425 | --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2426 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2427 | What does it print at the end? It is highly unlikely to ever print "Counter = 100000", because a thousand coroutines |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2428 | increment the `counter` concurrently from multiple threads without any synchronization. |
| 2429 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2430 | > Note: if you have an old system with 2 or fewer CPUs, then you _will_ consistently see 100000, because |
| 2431 | the thread pool is running in only one thread in this case. To reproduce the problem you'll need to make the |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 2432 | following change: |
| 2433 | |
| 2434 | ```kotlin |
| 2435 | val mtContext = newFixedThreadPoolContext(2, "mtPool") // explicitly define context with two threads |
| 2436 | var counter = 0 |
| 2437 | |
| 2438 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 2439 | CoroutineScope(mtContext).massiveRun { // use it instead of Dispatchers.Default in this sample and below |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 2440 | counter++ |
| 2441 | } |
| 2442 | println("Counter = $counter") |
| 2443 | } |
| 2444 | ``` |
| 2445 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2446 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-01b.kt) |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 2447 | |
| 2448 | <!--- TEST LINES_START |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2449 | Completed 100000 actions in |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 2450 | Counter = |
| 2451 | --> |
| 2452 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2453 | ### Volatiles are of no help |
| 2454 | |
| 2455 | There is common misconception that making a variable `volatile` solves concurrency problem. Let us try it: |
| 2456 | |
| 2457 | ```kotlin |
| 2458 | @Volatile // in Kotlin `volatile` is an annotation |
| 2459 | var counter = 0 |
| 2460 | |
| 2461 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2462 | GlobalScope.massiveRun { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2463 | counter++ |
| 2464 | } |
| 2465 | println("Counter = $counter") |
| 2466 | } |
| 2467 | ``` |
| 2468 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2469 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-02.kt) |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2470 | |
| 2471 | <!--- TEST LINES_START |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2472 | Completed 100000 actions in |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2473 | Counter = |
| 2474 | --> |
| 2475 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2476 | This code works slower, but we still don't get "Counter = 100000" at the end, because volatile variables guarantee |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2477 | linearizable (this is a technical term for "atomic") reads and writes to the corresponding variable, but |
| 2478 | do not provide atomicity of larger actions (increment in our case). |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2479 | |
| 2480 | ### Thread-safe data structures |
| 2481 | |
| 2482 | The general solution that works both for threads and for coroutines is to use a thread-safe (aka synchronized, |
| 2483 | linearizable, or atomic) data structure that provides all the necessarily synchronization for the corresponding |
| 2484 | operations that needs to be performed on a shared state. |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2485 | 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] | 2486 | |
| 2487 | ```kotlin |
| 2488 | var counter = AtomicInteger() |
| 2489 | |
| 2490 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2491 | GlobalScope.massiveRun { |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2492 | counter.incrementAndGet() |
| 2493 | } |
| 2494 | println("Counter = ${counter.get()}") |
| 2495 | } |
| 2496 | ``` |
| 2497 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2498 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-03.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2499 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2500 | <!--- TEST ARBITRARY_TIME |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2501 | Completed 100000 actions in xxx ms |
| 2502 | Counter = 100000 |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2503 | --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2504 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2505 | This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other |
| 2506 | standard data structures and basic operations on them. However, it does not easily scale to complex |
| 2507 | state or to complex operations that do not have ready-to-use thread-safe implementations. |
| 2508 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2509 | ### Thread confinement fine-grained |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2510 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2511 | _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] | 2512 | state is confined to a single thread. It is typically used in UI applications, where all UI state is confined to |
| 2513 | the single event-dispatch/application thread. It is easy to apply with coroutines by using a |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2514 | single-threaded context. |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2515 | |
| 2516 | ```kotlin |
| 2517 | val counterContext = newSingleThreadContext("CounterContext") |
| 2518 | var counter = 0 |
| 2519 | |
| 2520 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2521 | GlobalScope.massiveRun { // run each coroutine with DefaultDispathcer |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 2522 | withContext(counterContext) { // but confine each increment to the single-threaded context |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2523 | counter++ |
| 2524 | } |
| 2525 | } |
| 2526 | println("Counter = $counter") |
| 2527 | } |
| 2528 | ``` |
| 2529 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2530 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-04.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2531 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2532 | <!--- TEST ARBITRARY_TIME |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2533 | Completed 100000 actions in xxx ms |
| 2534 | Counter = 100000 |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2535 | --> |
| 2536 | |
| 2537 | This code works very slowly, because it does _fine-grained_ thread-confinement. Each individual increment switches |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 2538 | from multi-threaded [Dispatchers.Default] context to the single-threaded context using [withContext] block. |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2539 | |
| 2540 | ### Thread confinement coarse-grained |
| 2541 | |
| 2542 | In practice, thread confinement is performed in large chunks, e.g. big pieces of state-updating business logic |
| 2543 | are confined to the single thread. The following example does it like that, running each coroutine in |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2544 | the single-threaded context to start with. |
| 2545 | Here we use [CoroutineScope()] function to convert coroutine context reference to [CoroutineScope]: |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2546 | |
| 2547 | ```kotlin |
| 2548 | val counterContext = newSingleThreadContext("CounterContext") |
| 2549 | var counter = 0 |
| 2550 | |
| 2551 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2552 | CoroutineScope(counterContext).massiveRun { // run each coroutine in the single-threaded context |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2553 | counter++ |
| 2554 | } |
| 2555 | println("Counter = $counter") |
| 2556 | } |
| 2557 | ``` |
| 2558 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2559 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-05.kt) |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2560 | |
| 2561 | <!--- TEST ARBITRARY_TIME |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2562 | Completed 100000 actions in xxx ms |
| 2563 | Counter = 100000 |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2564 | --> |
| 2565 | |
| 2566 | This now works much faster and produces correct result. |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2567 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2568 | ### Mutual exclusion |
| 2569 | |
| 2570 | Mutual exclusion solution to the problem is to protect all modifications of the shared state with a _critical section_ |
| 2571 | that is never executed concurrently. In a blocking world you'd typically use `synchronized` or `ReentrantLock` for that. |
| 2572 | Coroutine's alternative is called [Mutex]. It has [lock][Mutex.lock] and [unlock][Mutex.unlock] functions to |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2573 | delimit a critical section. The key difference is that `Mutex.lock()` is a suspending function. It does not block a thread. |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2574 | |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 2575 | There is also [withLock] extension function that conveniently represents |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2576 | `mutex.lock(); try { ... } finally { mutex.unlock() }` pattern: |
| 2577 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2578 | ```kotlin |
| 2579 | val mutex = Mutex() |
| 2580 | var counter = 0 |
| 2581 | |
| 2582 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2583 | GlobalScope.massiveRun { |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2584 | mutex.withLock { |
| 2585 | counter++ |
| 2586 | } |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2587 | } |
| 2588 | println("Counter = $counter") |
| 2589 | } |
| 2590 | ``` |
| 2591 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2592 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-06.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2593 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2594 | <!--- TEST ARBITRARY_TIME |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2595 | Completed 100000 actions in xxx ms |
| 2596 | Counter = 100000 |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2597 | --> |
| 2598 | |
| 2599 | The locking in this example is fine-grained, so it pays the price. However, it is a good choice for some situations |
| 2600 | where you absolutely must modify some shared state periodically, but there is no natural thread that this state |
| 2601 | is confined to. |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2602 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2603 | ### Actors |
| 2604 | |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2605 | An [actor](https://en.wikipedia.org/wiki/Actor_model) is an entity made up of a combination of a coroutine, the state that is confined and encapsulated into this coroutine, |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2606 | and a channel to communicate with other coroutines. A simple actor can be written as a function, |
| 2607 | but an actor with a complex state is better suited for a class. |
| 2608 | |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2609 | There is an [actor] coroutine builder that conveniently combines actor's mailbox channel into its |
| 2610 | scope to receive messages from and combines the send channel into the resulting job object, so that a |
| 2611 | single reference to the actor can be carried around as its handle. |
| 2612 | |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2613 | The first step of using an actor is to define a class of messages that an actor is going to process. |
| 2614 | Kotlin's [sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) are well suited for that purpose. |
| 2615 | We define `CounterMsg` sealed class with `IncCounter` message to increment a counter and `GetCounter` message |
| 2616 | to get its value. The later needs to send a response. A [CompletableDeferred] communication |
| 2617 | primitive, that represents a single value that will be known (communicated) in the future, |
| 2618 | is used here for that purpose. |
| 2619 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2620 | ```kotlin |
| 2621 | // Message types for counterActor |
| 2622 | sealed class CounterMsg |
| 2623 | object IncCounter : CounterMsg() // one-way message to increment counter |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2624 | class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // a request with reply |
| 2625 | ``` |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2626 | |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2627 | Then we define a function that launches an actor using an [actor] coroutine builder: |
| 2628 | |
| 2629 | ```kotlin |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2630 | // This function launches a new counter actor |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2631 | fun CoroutineScope.counterActor() = actor<CounterMsg> { |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2632 | var counter = 0 // actor state |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2633 | for (msg in channel) { // iterate over incoming messages |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2634 | when (msg) { |
| 2635 | is IncCounter -> counter++ |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2636 | is GetCounter -> msg.response.complete(counter) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2637 | } |
| 2638 | } |
| 2639 | } |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2640 | ``` |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2641 | |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2642 | The main code is straightforward: |
| 2643 | |
| 2644 | ```kotlin |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2645 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2646 | val counter = counterActor() // create the actor |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2647 | GlobalScope.massiveRun { |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2648 | counter.send(IncCounter) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2649 | } |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2650 | // send a message to get a counter value from an actor |
| 2651 | val response = CompletableDeferred<Int>() |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2652 | counter.send(GetCounter(response)) |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2653 | println("Counter = ${response.await()}") |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2654 | counter.close() // shutdown the actor |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2655 | } |
| 2656 | ``` |
| 2657 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2658 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-07.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2659 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2660 | <!--- TEST ARBITRARY_TIME |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2661 | Completed 100000 actions in xxx ms |
| 2662 | Counter = 100000 |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2663 | --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2664 | |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2665 | 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] | 2666 | a coroutine and a coroutine is executed sequentially, so confinement of the state to the specific coroutine |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2667 | works as a solution to the problem of shared mutable state. Indeed, actors may modify their own private state, but can only affect each other through messages (avoiding the need for any locks). |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2668 | |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2669 | Actor is more efficient than locking under load, because in this case it always has work to do and it does not |
| 2670 | have to switch to a different context at all. |
| 2671 | |
| 2672 | > Note, that an [actor] coroutine builder is a dual of [produce] coroutine builder. An actor is associated |
| 2673 | with the channel that it receives messages from, while a producer is associated with the channel that it |
| 2674 | sends elements to. |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2675 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2676 | ## Select expression (experimental) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2677 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2678 | 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] | 2679 | the first one that becomes available. |
| 2680 | |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2681 | > Select expressions are an experimental feature of `kotlinx.coroutines`. Their API is expected to |
| 2682 | evolve in the upcoming updates of the `kotlinx.coroutines` library with potentially |
| 2683 | breaking changes. |
| 2684 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2685 | <!--- INCLUDE .*/example-select-([0-9]+).kt |
| 2686 | import kotlinx.coroutines.experimental.channels.* |
| 2687 | import kotlinx.coroutines.experimental.selects.* |
| 2688 | --> |
| 2689 | |
| 2690 | ### Selecting from channels |
| 2691 | |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2692 | Let us have two producers of strings: `fizz` and `buzz`. The `fizz` produces "Fizz" string every 300 ms: |
| 2693 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2694 | <!--- INCLUDE |
| 2695 | import kotlinx.coroutines.experimental.* |
| 2696 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2697 | --> |
| 2698 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2699 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2700 | fun CoroutineScope.fizz() = produce<String> { |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2701 | while (true) { // sends "Fizz" every 300 ms |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2702 | delay(300) |
| 2703 | send("Fizz") |
| 2704 | } |
| 2705 | } |
| 2706 | ``` |
| 2707 | |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2708 | And the `buzz` produces "Buzz!" string every 500 ms: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2709 | |
| 2710 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2711 | fun CoroutineScope.buzz() = produce<String> { |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2712 | while (true) { // sends "Buzz!" every 500 ms |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2713 | delay(500) |
| 2714 | send("Buzz!") |
| 2715 | } |
| 2716 | } |
| 2717 | ``` |
| 2718 | |
| 2719 | Using [receive][ReceiveChannel.receive] suspending function we can receive _either_ from one channel or the |
| 2720 | other. But [select] expression allows us to receive from _both_ simultaneously using its |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2721 | [onReceive][ReceiveChannel.onReceive] clauses: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2722 | |
| 2723 | ```kotlin |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2724 | suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2725 | select<Unit> { // <Unit> means that this select expression does not produce any result |
| 2726 | fizz.onReceive { value -> // this is the first select clause |
| 2727 | println("fizz -> '$value'") |
| 2728 | } |
| 2729 | buzz.onReceive { value -> // this is the second select clause |
| 2730 | println("buzz -> '$value'") |
| 2731 | } |
| 2732 | } |
| 2733 | } |
| 2734 | ``` |
| 2735 | |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2736 | Let us run it all seven times: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2737 | |
| 2738 | ```kotlin |
| 2739 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2740 | val fizz = fizz() |
| 2741 | val buzz = buzz() |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2742 | repeat(7) { |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2743 | selectFizzBuzz(fizz, buzz) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2744 | } |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2745 | coroutineContext.cancelChildren() // cancel fizz & buzz coroutines |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2746 | } |
| 2747 | ``` |
| 2748 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2749 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-select-01.kt) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2750 | |
| 2751 | The result of this code is: |
| 2752 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2753 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2754 | fizz -> 'Fizz' |
| 2755 | buzz -> 'Buzz!' |
| 2756 | fizz -> 'Fizz' |
| 2757 | fizz -> 'Fizz' |
| 2758 | buzz -> 'Buzz!' |
| 2759 | fizz -> 'Fizz' |
| 2760 | buzz -> 'Buzz!' |
| 2761 | ``` |
| 2762 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2763 | <!--- TEST --> |
| 2764 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2765 | ### Selecting on close |
| 2766 | |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2767 | The [onReceive][ReceiveChannel.onReceive] clause in `select` fails when the channel is closed causing the corresponding |
| 2768 | `select` to throw an exception. We can use [onReceiveOrNull][ReceiveChannel.onReceiveOrNull] clause to perform a |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2769 | 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] | 2770 | the result of its selected clause: |
| 2771 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2772 | <!--- INCLUDE |
| 2773 | import kotlin.coroutines.experimental.* |
| 2774 | --> |
| 2775 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2776 | ```kotlin |
| 2777 | suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String = |
| 2778 | select<String> { |
| 2779 | a.onReceiveOrNull { value -> |
| 2780 | if (value == null) |
| 2781 | "Channel 'a' is closed" |
| 2782 | else |
| 2783 | "a -> '$value'" |
| 2784 | } |
| 2785 | b.onReceiveOrNull { value -> |
| 2786 | if (value == null) |
| 2787 | "Channel 'b' is closed" |
| 2788 | else |
| 2789 | "b -> '$value'" |
| 2790 | } |
| 2791 | } |
| 2792 | ``` |
| 2793 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2794 | Let's use it with channel `a` that produces "Hello" string four times and |
| 2795 | channel `b` that produces "World" four times: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2796 | |
| 2797 | ```kotlin |
| 2798 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2799 | val a = produce<String> { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2800 | repeat(4) { send("Hello $it") } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2801 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2802 | val b = produce<String> { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2803 | repeat(4) { send("World $it") } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2804 | } |
| 2805 | repeat(8) { // print first eight results |
| 2806 | println(selectAorB(a, b)) |
| 2807 | } |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2808 | coroutineContext.cancelChildren() |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2809 | } |
| 2810 | ``` |
| 2811 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2812 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-select-02.kt) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2813 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2814 | 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] | 2815 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2816 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2817 | a -> 'Hello 0' |
| 2818 | a -> 'Hello 1' |
| 2819 | b -> 'World 0' |
| 2820 | a -> 'Hello 2' |
| 2821 | a -> 'Hello 3' |
| 2822 | b -> 'World 1' |
| 2823 | Channel 'a' is closed |
| 2824 | Channel 'a' is closed |
| 2825 | ``` |
| 2826 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2827 | <!--- TEST --> |
| 2828 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2829 | There are couple of observations to make out of it. |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2830 | |
| 2831 | First of all, `select` is _biased_ to the first clause. When several clauses are selectable at the same time, |
| 2832 | 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] | 2833 | 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] | 2834 | time to time on its [send][SendChannel.send] invocation and gives a chance for `b` to send, too. |
| 2835 | |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2836 | The second observation, is that [onReceiveOrNull][ReceiveChannel.onReceiveOrNull] gets immediately selected when the |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2837 | channel is already closed. |
| 2838 | |
| 2839 | ### Selecting to send |
| 2840 | |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2841 | Select expression has [onSend][SendChannel.onSend] clause that can be used for a great good in combination |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2842 | with a biased nature of selection. |
| 2843 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2844 | 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] | 2845 | the consumers on its primary channel cannot keep up with it: |
| 2846 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2847 | <!--- INCLUDE |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2848 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2849 | --> |
| 2850 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2851 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2852 | fun CoroutineScope.produceNumbers(side: SendChannel<Int>) = produce<Int> { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2853 | for (num in 1..10) { // produce 10 numbers from 1 to 10 |
| 2854 | delay(100) // every 100 ms |
| 2855 | select<Unit> { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2856 | onSend(num) {} // Send to the primary channel |
| 2857 | side.onSend(num) {} // or to the side channel |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2858 | } |
| 2859 | } |
| 2860 | } |
| 2861 | ``` |
| 2862 | |
| 2863 | Consumer is going to be quite slow, taking 250 ms to process each number: |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2864 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2865 | ```kotlin |
| 2866 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2867 | val side = Channel<Int>() // allocate side channel |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2868 | launch { // this is a very fast consumer for the side channel |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 2869 | side.consumeEach { println("Side channel has $it") } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2870 | } |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2871 | produceNumbers(side).consumeEach { |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 2872 | println("Consuming $it") |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2873 | delay(250) // let us digest the consumed number properly, do not hurry |
| 2874 | } |
| 2875 | println("Done consuming") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2876 | coroutineContext.cancelChildren() |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2877 | } |
| 2878 | ``` |
| 2879 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2880 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-select-03.kt) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2881 | |
| 2882 | So let us see what happens: |
| 2883 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2884 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2885 | Consuming 1 |
| 2886 | Side channel has 2 |
| 2887 | Side channel has 3 |
| 2888 | Consuming 4 |
| 2889 | Side channel has 5 |
| 2890 | Side channel has 6 |
| 2891 | Consuming 7 |
| 2892 | Side channel has 8 |
| 2893 | Side channel has 9 |
| 2894 | Consuming 10 |
| 2895 | Done consuming |
| 2896 | ``` |
| 2897 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2898 | <!--- TEST --> |
| 2899 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2900 | ### Selecting deferred values |
| 2901 | |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2902 | Deferred values can be selected using [onAwait][Deferred.onAwait] clause. |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2903 | 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] | 2904 | a random delay: |
| 2905 | |
| 2906 | <!--- INCLUDE .*/example-select-04.kt |
| 2907 | import java.util.* |
| 2908 | --> |
| 2909 | |
| 2910 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2911 | fun CoroutineScope.asyncString(time: Int) = async { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2912 | delay(time.toLong()) |
| 2913 | "Waited for $time ms" |
| 2914 | } |
| 2915 | ``` |
| 2916 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2917 | Let us start a dozen of them with a random delay. |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2918 | |
| 2919 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2920 | fun CoroutineScope.asyncStringsList(): List<Deferred<String>> { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2921 | val random = Random(3) |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2922 | return List(12) { asyncString(random.nextInt(1000)) } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2923 | } |
| 2924 | ``` |
| 2925 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2926 | 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] | 2927 | 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] | 2928 | so we can provide clauses for it using an arbitrary code. In this case we iterate over a list |
| 2929 | of deferred values to provide `onAwait` clause for each deferred value. |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2930 | |
| 2931 | ```kotlin |
| 2932 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2933 | val list = asyncStringsList() |
| 2934 | val result = select<String> { |
| 2935 | list.withIndex().forEach { (index, deferred) -> |
| 2936 | deferred.onAwait { answer -> |
| 2937 | "Deferred $index produced answer '$answer'" |
| 2938 | } |
| 2939 | } |
| 2940 | } |
| 2941 | println(result) |
Roman Elizarov | 7c864d8 | 2017-02-27 10:17:50 +0300 | [diff] [blame] | 2942 | val countActive = list.count { it.isActive } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2943 | println("$countActive coroutines are still active") |
| 2944 | } |
| 2945 | ``` |
| 2946 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2947 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-select-04.kt) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2948 | |
| 2949 | The output is: |
| 2950 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2951 | ```text |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2952 | Deferred 4 produced answer 'Waited for 128 ms' |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2953 | 11 coroutines are still active |
| 2954 | ``` |
| 2955 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2956 | <!--- TEST --> |
| 2957 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2958 | ### Switch over a channel of deferred values |
| 2959 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2960 | Let us write a channel producer function that consumes a channel of deferred string values, waits for each received |
| 2961 | deferred value, but only until the next deferred value comes over or the channel is closed. This example puts together |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2962 | [onReceiveOrNull][ReceiveChannel.onReceiveOrNull] and [onAwait][Deferred.onAwait] clauses in the same `select`: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2963 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2964 | <!--- INCLUDE |
| 2965 | import kotlin.coroutines.experimental.* |
| 2966 | --> |
| 2967 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2968 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2969 | fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2970 | var current = input.receive() // start with first received deferred value |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2971 | while (isActive) { // loop while not cancelled/closed |
| 2972 | val next = select<Deferred<String>?> { // return next deferred value from this select or null |
| 2973 | input.onReceiveOrNull { update -> |
| 2974 | update // replaces next value to wait |
| 2975 | } |
| 2976 | current.onAwait { value -> |
| 2977 | send(value) // send value that current deferred has produced |
| 2978 | input.receiveOrNull() // and use the next deferred from the input channel |
| 2979 | } |
| 2980 | } |
| 2981 | if (next == null) { |
| 2982 | println("Channel was closed") |
| 2983 | break // out of loop |
| 2984 | } else { |
| 2985 | current = next |
| 2986 | } |
| 2987 | } |
| 2988 | } |
| 2989 | ``` |
| 2990 | |
| 2991 | To test it, we'll use a simple async function that resolves to a specified string after a specified time: |
| 2992 | |
| 2993 | ```kotlin |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 2994 | fun CoroutineScope.asyncString(str: String, time: Long) = async { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2995 | delay(time) |
| 2996 | str |
| 2997 | } |
| 2998 | ``` |
| 2999 | |
| 3000 | The main function just launches a coroutine to print results of `switchMapDeferreds` and sends some test |
| 3001 | data to it: |
| 3002 | |
| 3003 | ```kotlin |
| 3004 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 3005 | val chan = Channel<Deferred<String>>() // the channel for test |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 3006 | launch { // launch printing coroutine |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3007 | for (s in switchMapDeferreds(chan)) |
| 3008 | println(s) // print each received string |
| 3009 | } |
| 3010 | chan.send(asyncString("BEGIN", 100)) |
| 3011 | delay(200) // enough time for "BEGIN" to be produced |
| 3012 | chan.send(asyncString("Slow", 500)) |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 3013 | delay(100) // not enough time to produce slow |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3014 | chan.send(asyncString("Replace", 100)) |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 3015 | delay(500) // give it time before the last one |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3016 | chan.send(asyncString("END", 500)) |
| 3017 | delay(1000) // give it time to process |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 3018 | chan.close() // close the channel ... |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3019 | delay(500) // and wait some time to let it finish |
| 3020 | } |
| 3021 | ``` |
| 3022 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 3023 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-select-05.kt) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3024 | |
| 3025 | The result of this code: |
| 3026 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 3027 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3028 | BEGIN |
| 3029 | Replace |
| 3030 | END |
| 3031 | Channel was closed |
| 3032 | ``` |
| 3033 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 3034 | <!--- TEST --> |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3035 | |
Roman Elizarov | 8db1733 | 2017-03-09 12:40:45 +0300 | [diff] [blame] | 3036 | ## Further reading |
| 3037 | |
| 3038 | * [Guide to UI programming with coroutines](ui/coroutines-guide-ui.md) |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 3039 | * [Guide to reactive streams with coroutines](reactive/coroutines-guide-reactive.md) |
Roman Elizarov | 8db1733 | 2017-03-09 12:40:45 +0300 | [diff] [blame] | 3040 | * [Coroutines design document (KEEP)](https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md) |
| 3041 | * [Full kotlinx.coroutines API reference](http://kotlin.github.io/kotlinx.coroutines) |
| 3042 | |
Roman Elizarov | e7e2ad1 | 2017-05-17 14:47:31 +0300 | [diff] [blame] | 3043 | <!--- MODULE kotlinx-coroutines-core --> |
Roman Elizarov | e0c817d | 2017-02-10 10:22:01 +0300 | [diff] [blame] | 3044 | <!--- INDEX kotlinx.coroutines.experimental --> |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3045 | [launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/launch.html |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 3046 | [CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/index.html |
| 3047 | [GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-global-scope/index.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3048 | [delay]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/delay.html |
| 3049 | [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] | 3050 | [Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/index.html |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 3051 | [Job.join]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/join.html |
| 3052 | [coroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/coroutine-scope.html |
| 3053 | [currentScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/current-scope.html |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 3054 | [cancelAndJoin]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/cancel-and-join.html |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 3055 | [Job.cancel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/cancel.html |
Roman Elizarov | cbb602d | 2017-12-23 14:24:26 +0300 | [diff] [blame] | 3056 | [CancellationException]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-cancellation-exception/index.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3057 | [yield]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/yield.html |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 3058 | [isActive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/is-active.html |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 3059 | [withContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-context.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3060 | [NonCancellable]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-non-cancellable/index.html |
| 3061 | [withTimeout]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-timeout.html |
Roman Elizarov | 63f6ea2 | 2017-09-06 18:42:34 +0300 | [diff] [blame] | 3062 | [withTimeoutOrNull]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-timeout-or-null.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3063 | [async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/async.html |
| 3064 | [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] | 3065 | [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] | 3066 | [Deferred.await]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/await.html |
| 3067 | [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] | 3068 | [CoroutineDispatcher]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-dispatcher/index.html |
Roman Elizarov | dc29b07 | 2018-09-11 18:42:03 +0300 | [diff] [blame^] | 3069 | [Dispatchers.Unconfined]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-dispatchers/-unconfined.html |
| 3070 | [Dispatchers.Default]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-dispatchers/-default.html |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 3071 | [newSingleThreadContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/new-single-thread-context.html |
| 3072 | [ThreadPoolDispatcher.close]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-thread-pool-dispatcher/close.html |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 3073 | [newCoroutineContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/new-coroutine-context.html |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 3074 | [CoroutineScope.coroutineContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/coroutine-context.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3075 | [CoroutineName]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-name/index.html |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 3076 | [Job()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job.html |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame] | 3077 | [asContextElement]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/java.lang.-thread-local/as-context-element.html |
| 3078 | [ThreadContextElement]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-thread-context-element/index.html |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 3079 | [CoroutineExceptionHandler]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-exception-handler/index.html |
Roman Elizarov | 3e387b8 | 2017-12-04 13:49:11 +0300 | [diff] [blame] | 3080 | [kotlin.coroutines.experimental.CoroutineContext.cancelChildren]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/kotlin.coroutines.experimental.-coroutine-context/cancel-children.html |
Roman Elizarov | c32579e | 2018-09-09 19:21:43 +0300 | [diff] [blame] | 3081 | [CoroutineScope()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope.html |
Roman Elizarov | e82dee7 | 2017-08-18 16:49:09 +0300 | [diff] [blame] | 3082 | [CompletableDeferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-completable-deferred/index.html |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 3083 | [Deferred.onAwait]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/on-await.html |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 3084 | <!--- INDEX kotlinx.coroutines.experimental.sync --> |
Roman Elizarov | e82dee7 | 2017-08-18 16:49:09 +0300 | [diff] [blame] | 3085 | [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] | 3086 | [Mutex.lock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/lock.html |
| 3087 | [Mutex.unlock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/unlock.html |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 3088 | [withLock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/with-lock.html |
Roman Elizarov | e0c817d | 2017-02-10 10:22:01 +0300 | [diff] [blame] | 3089 | <!--- INDEX kotlinx.coroutines.experimental.channels --> |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 3090 | [actor]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/actor.html |
| 3091 | [produce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/produce.html |
| 3092 | [ReceiveChannel.receive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-receive-channel/receive.html |
Roman Elizarov | e82dee7 | 2017-08-18 16:49:09 +0300 | [diff] [blame] | 3093 | [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] | 3094 | [SendChannel.send]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/send.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 3095 | [SendChannel.close]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/close.html |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 3096 | [consumeEach]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/consume-each.html |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 3097 | [Channel()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-channel.html |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 3098 | [ticker]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/ticker.html |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 3099 | [ReceiveChannel.cancel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-receive-channel/cancel.html |
Roman Elizarov | 0c090ed | 2018-06-29 19:51:07 +0300 | [diff] [blame] | 3100 | [TickerMode.FIXED_DELAY]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-ticker-mode/-f-i-x-e-d_-d-e-l-a-y.html |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 3101 | [ReceiveChannel.onReceive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-receive-channel/on-receive.html |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 3102 | [ReceiveChannel.onReceiveOrNull]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-receive-channel/on-receive-or-null.html |
| 3103 | [SendChannel.onSend]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/on-send.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 3104 | <!--- INDEX kotlinx.coroutines.experimental.selects --> |
| 3105 | [select]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/select.html |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 3106 | <!--- END --> |