blob: 7574e46d8ec5ba74decb8c7148074c4fc8ec3771 [file] [log] [blame] [view]
hadihariri7db55532018-09-15 10:35:08 +02001<!--- INCLUDE .*/example-([a-z]+)-([0-9a-z]+)\.kt
2/*
3 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
4 */
5
6// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
7package kotlinx.coroutines.experimental.guide.$$1$$2
8
9import kotlinx.coroutines.experimental.*
10-->
11<!--- KNIT ../core/kotlinx-coroutines-core/test/guide/.*\.kt -->
12<!--- TEST_OUT ../core/kotlinx-coroutines-core/test/guide/test/SharedStateGuideTest.kt
13// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
14package kotlinx.coroutines.experimental.guide.test
15
16import org.junit.Test
17
18class SharedStateGuideTest {
19-->
20## Table of contents
21
22<!--- TOC -->
23
24* [Shared mutable state and concurrency](#shared-mutable-state-and-concurrency)
25 * [The problem](#the-problem)
26 * [Volatiles are of no help](#volatiles-are-of-no-help)
27 * [Thread-safe data structures](#thread-safe-data-structures)
28 * [Thread confinement fine-grained](#thread-confinement-fine-grained)
29 * [Thread confinement coarse-grained](#thread-confinement-coarse-grained)
30 * [Mutual exclusion](#mutual-exclusion)
31 * [Actors](#actors)
32
33<!--- END_TOC -->
34
35## Shared mutable state and concurrency
36
37Coroutines can be executed concurrently using a multi-threaded dispatcher like the [Dispatchers.Default]. It presents
38all the usual concurrency problems. The main problem being synchronization of access to **shared mutable state**.
39Some solutions to this problem in the land of coroutines are similar to the solutions in the multi-threaded world,
40but others are unique.
41
42### The problem
43
44Let us launch a hundred coroutines all doing the same action thousand times.
45We'll also measure their completion time for further comparisons:
46
47<!--- INCLUDE .*/example-sync-03.kt
48import java.util.concurrent.atomic.*
49-->
50
51<!--- INCLUDE .*/example-sync-06.kt
52import kotlinx.coroutines.experimental.sync.*
53-->
54
55<!--- INCLUDE .*/example-sync-07.kt
56import kotlinx.coroutines.experimental.channels.*
57-->
58
59<!--- INCLUDE .*/example-sync-([0-9a-z]+).kt
60import kotlin.system.*
61import kotlin.coroutines.experimental.*
62-->
63
64```kotlin
65suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) {
66 val n = 100 // number of coroutines to launch
67 val k = 1000 // times an action is repeated by each coroutine
68 val time = measureTimeMillis {
69 val jobs = List(n) {
70 launch {
71 repeat(k) { action() }
72 }
73 }
74 jobs.forEach { it.join() }
75 }
76 println("Completed ${n * k} actions in $time ms")
77}
78```
79
80<!--- INCLUDE .*/example-sync-([0-9a-z]+).kt -->
81
82We start with a very simple action that increments a shared mutable variable using
83multi-threaded [Dispatchers.Default] that is used in [GlobalScope].
84
85```kotlin
86var counter = 0
87
88fun main(args: Array<String>) = runBlocking<Unit> {
89 GlobalScope.massiveRun {
90 counter++
91 }
92 println("Counter = $counter")
93}
94```
95
96> You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-01.kt)
97
98<!--- TEST LINES_START
99Completed 100000 actions in
100Counter =
101-->
102
103What does it print at the end? It is highly unlikely to ever print "Counter = 100000", because a thousand coroutines
104increment the `counter` concurrently from multiple threads without any synchronization.
105
106> Note: if you have an old system with 2 or fewer CPUs, then you _will_ consistently see 100000, because
107the thread pool is running in only one thread in this case. To reproduce the problem you'll need to make the
108following change:
109
110```kotlin
111val mtContext = newFixedThreadPoolContext(2, "mtPool") // explicitly define context with two threads
112var counter = 0
113
114fun main(args: Array<String>) = runBlocking<Unit> {
115 CoroutineScope(mtContext).massiveRun { // use it instead of Dispatchers.Default in this sample and below
116 counter++
117 }
118 println("Counter = $counter")
119}
120```
121
122> You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-01b.kt)
123
124<!--- TEST LINES_START
125Completed 100000 actions in
126Counter =
127-->
128
129### Volatiles are of no help
130
131There is common misconception that making a variable `volatile` solves concurrency problem. Let us try it:
132
133```kotlin
134@Volatile // in Kotlin `volatile` is an annotation
135var counter = 0
136
137fun main(args: Array<String>) = runBlocking<Unit> {
138 GlobalScope.massiveRun {
139 counter++
140 }
141 println("Counter = $counter")
142}
143```
144
145> You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-02.kt)
146
147<!--- TEST LINES_START
148Completed 100000 actions in
149Counter =
150-->
151
152This code works slower, but we still don't get "Counter = 100000" at the end, because volatile variables guarantee
153linearizable (this is a technical term for "atomic") reads and writes to the corresponding variable, but
154do not provide atomicity of larger actions (increment in our case).
155
156### Thread-safe data structures
157
158The general solution that works both for threads and for coroutines is to use a thread-safe (aka synchronized,
159linearizable, or atomic) data structure that provides all the necessarily synchronization for the corresponding
160operations that needs to be performed on a shared state.
161In the case of a simple counter we can use `AtomicInteger` class which has atomic `incrementAndGet` operations:
162
163```kotlin
164var counter = AtomicInteger()
165
166fun main(args: Array<String>) = runBlocking<Unit> {
167 GlobalScope.massiveRun {
168 counter.incrementAndGet()
169 }
170 println("Counter = ${counter.get()}")
171}
172```
173
174> You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-03.kt)
175
176<!--- TEST ARBITRARY_TIME
177Completed 100000 actions in xxx ms
178Counter = 100000
179-->
180
181This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other
182standard data structures and basic operations on them. However, it does not easily scale to complex
183state or to complex operations that do not have ready-to-use thread-safe implementations.
184
185### Thread confinement fine-grained
186
187_Thread confinement_ is an approach to the problem of shared mutable state where all access to the particular shared
188state is confined to a single thread. It is typically used in UI applications, where all UI state is confined to
189the single event-dispatch/application thread. It is easy to apply with coroutines by using a
190single-threaded context.
191
192```kotlin
193val counterContext = newSingleThreadContext("CounterContext")
194var counter = 0
195
196fun main(args: Array<String>) = runBlocking<Unit> {
197 GlobalScope.massiveRun { // run each coroutine with DefaultDispathcer
198 withContext(counterContext) { // but confine each increment to the single-threaded context
199 counter++
200 }
201 }
202 println("Counter = $counter")
203}
204```
205
206> You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-04.kt)
207
208<!--- TEST ARBITRARY_TIME
209Completed 100000 actions in xxx ms
210Counter = 100000
211-->
212
213This code works very slowly, because it does _fine-grained_ thread-confinement. Each individual increment switches
214from multi-threaded [Dispatchers.Default] context to the single-threaded context using [withContext] block.
215
216### Thread confinement coarse-grained
217
218In practice, thread confinement is performed in large chunks, e.g. big pieces of state-updating business logic
219are confined to the single thread. The following example does it like that, running each coroutine in
220the single-threaded context to start with.
221Here we use [CoroutineScope()] function to convert coroutine context reference to [CoroutineScope]:
222
223```kotlin
224val counterContext = newSingleThreadContext("CounterContext")
225var counter = 0
226
227fun main(args: Array<String>) = runBlocking<Unit> {
228 CoroutineScope(counterContext).massiveRun { // run each coroutine in the single-threaded context
229 counter++
230 }
231 println("Counter = $counter")
232}
233```
234
235> You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-05.kt)
236
237<!--- TEST ARBITRARY_TIME
238Completed 100000 actions in xxx ms
239Counter = 100000
240-->
241
242This now works much faster and produces correct result.
243
244### Mutual exclusion
245
246Mutual exclusion solution to the problem is to protect all modifications of the shared state with a _critical section_
247that is never executed concurrently. In a blocking world you'd typically use `synchronized` or `ReentrantLock` for that.
248Coroutine's alternative is called [Mutex]. It has [lock][Mutex.lock] and [unlock][Mutex.unlock] functions to
249delimit a critical section. The key difference is that `Mutex.lock()` is a suspending function. It does not block a thread.
250
251There is also [withLock] extension function that conveniently represents
252`mutex.lock(); try { ... } finally { mutex.unlock() }` pattern:
253
254```kotlin
255val mutex = Mutex()
256var counter = 0
257
258fun main(args: Array<String>) = runBlocking<Unit> {
259 GlobalScope.massiveRun {
260 mutex.withLock {
261 counter++
262 }
263 }
264 println("Counter = $counter")
265}
266```
267
268> You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-06.kt)
269
270<!--- TEST ARBITRARY_TIME
271Completed 100000 actions in xxx ms
272Counter = 100000
273-->
274
275The locking in this example is fine-grained, so it pays the price. However, it is a good choice for some situations
276where you absolutely must modify some shared state periodically, but there is no natural thread that this state
277is confined to.
278
279### Actors
280
281An [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,
282and a channel to communicate with other coroutines. A simple actor can be written as a function,
283but an actor with a complex state is better suited for a class.
284
285There is an [actor] coroutine builder that conveniently combines actor's mailbox channel into its
286scope to receive messages from and combines the send channel into the resulting job object, so that a
287single reference to the actor can be carried around as its handle.
288
289The first step of using an actor is to define a class of messages that an actor is going to process.
290Kotlin's [sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) are well suited for that purpose.
291We define `CounterMsg` sealed class with `IncCounter` message to increment a counter and `GetCounter` message
292to get its value. The later needs to send a response. A [CompletableDeferred] communication
293primitive, that represents a single value that will be known (communicated) in the future,
294is used here for that purpose.
295
296```kotlin
297// Message types for counterActor
298sealed class CounterMsg
299object IncCounter : CounterMsg() // one-way message to increment counter
300class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // a request with reply
301```
302
303Then we define a function that launches an actor using an [actor] coroutine builder:
304
305```kotlin
306// This function launches a new counter actor
307fun CoroutineScope.counterActor() = actor<CounterMsg> {
308 var counter = 0 // actor state
309 for (msg in channel) { // iterate over incoming messages
310 when (msg) {
311 is IncCounter -> counter++
312 is GetCounter -> msg.response.complete(counter)
313 }
314 }
315}
316```
317
318The main code is straightforward:
319
320```kotlin
321fun main(args: Array<String>) = runBlocking<Unit> {
322 val counter = counterActor() // create the actor
323 GlobalScope.massiveRun {
324 counter.send(IncCounter)
325 }
326 // send a message to get a counter value from an actor
327 val response = CompletableDeferred<Int>()
328 counter.send(GetCounter(response))
329 println("Counter = ${response.await()}")
330 counter.close() // shutdown the actor
331}
332```
333
334> You can get full code [here](../core/kotlinx-coroutines-core/test/guide/example-sync-07.kt)
335
336<!--- TEST ARBITRARY_TIME
337Completed 100000 actions in xxx ms
338Counter = 100000
339-->
340
341It does not matter (for correctness) what context the actor itself is executed in. An actor is
342a coroutine and a coroutine is executed sequentially, so confinement of the state to the specific coroutine
343works 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).
344
345Actor is more efficient than locking under load, because in this case it always has work to do and it does not
346have to switch to a different context at all.
347
348> Note, that an [actor] coroutine builder is a dual of [produce] coroutine builder. An actor is associated
349 with the channel that it receives messages from, while a producer is associated with the channel that it
350 sends elements to.
Roman Elizarov99c28aa2018-09-23 18:42:36 +0300351
352<!--- MODULE kotlinx-coroutines-core -->
353<!--- INDEX kotlinx.coroutines.experimental -->
354[Dispatchers.Default]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-dispatchers/-default.html
355[GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-global-scope/index.html
356[withContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-context.html
357[CoroutineScope()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope.html
358[CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/index.html
359[CompletableDeferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-completable-deferred/index.html
360<!--- INDEX kotlinx.coroutines.experimental.sync -->
361[Mutex]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/index.html
362[Mutex.lock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/lock.html
363[Mutex.unlock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/unlock.html
364[withLock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/with-lock.html
365<!--- INDEX kotlinx.coroutines.experimental.channels -->
366[actor]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/actor.html
367[produce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/produce.html
368<!--- END -->