0
# Dispatchers
1
2
Thread pool implementations providing different execution contexts for coroutines, with JVM-specific optimizations and configurable parallelism.
3
4
## Capabilities
5
6
### Dispatchers Object
7
8
Central object providing access to various coroutine dispatcher implementations.
9
10
```kotlin { .api }
11
object Dispatchers {
12
/** Dispatcher for CPU-intensive tasks */
13
val Default: CoroutineDispatcher
14
15
/** Dispatcher for UI thread operations */
16
val Main: MainCoroutineDispatcher
17
18
/** Dispatcher for blocking I/O operations (JVM-specific) */
19
val IO: CoroutineDispatcher
20
21
/** Unconfined dispatcher that starts in caller context */
22
val Unconfined: CoroutineDispatcher
23
24
/** Shuts down built-in dispatchers (delicate API) */
25
@DelicateCoroutinesApi
26
fun shutdown()
27
}
28
```
29
30
**Usage Examples:**
31
32
```kotlin
33
import kotlinx.coroutines.*
34
35
fun main() = runBlocking {
36
// Different dispatchers for different tasks
37
38
// CPU-intensive computation
39
val result1 = withContext(Dispatchers.Default) {
40
(1..1000000).sum()
41
}
42
43
// Blocking I/O operation
44
val result2 = withContext(Dispatchers.IO) {
45
java.io.File("data.txt").readText()
46
}
47
48
// Unconfined - starts in current context
49
withContext(Dispatchers.Unconfined) {
50
println("Current thread: ${Thread.currentThread().name}")
51
delay(100) // May resume on different thread
52
println("After delay: ${Thread.currentThread().name}")
53
}
54
}
55
```
56
57
### Dispatchers.Default
58
59
Optimized for CPU-intensive tasks, backed by a shared thread pool with parallelism equal to the number of CPU cores.
60
61
```kotlin { .api }
62
val Dispatchers.Default: CoroutineDispatcher
63
```
64
65
**Usage Examples:**
66
67
```kotlin
68
import kotlinx.coroutines.*
69
70
suspend fun heavyComputation(): Long = withContext(Dispatchers.Default) {
71
// CPU-intensive task
72
(1..10_000_000).fold(0L) { acc, i -> acc + i * i }
73
}
74
75
fun main() = runBlocking {
76
val jobs = List(4) {
77
async(Dispatchers.Default) {
78
heavyComputation()
79
}
80
}
81
82
val results = jobs.awaitAll()
83
println("Results: $results")
84
}
85
```
86
87
### Dispatchers.IO (JVM-specific)
88
89
Optimized for blocking I/O operations with elastic thread pool that can grow as needed, with configurable parallelism.
90
91
```kotlin { .api }
92
val Dispatchers.IO: CoroutineDispatcher
93
94
/** Property name for configuring IO parallelism */
95
const val IO_PARALLELISM_PROPERTY_NAME: String = "kotlinx.coroutines.io.parallelism"
96
```
97
98
**Key Features:**
99
- Default parallelism: max(64, number of CPU cores)
100
- Elastic thread pool that creates threads on demand
101
- Shares threads with Default dispatcher when possible
102
- Supports `limitedParallelism()` for creating custom thread pools
103
104
**Usage Examples:**
105
106
```kotlin
107
import kotlinx.coroutines.*
108
import java.io.File
109
110
suspend fun readFiles(filenames: List<String>): List<String> =
111
filenames.map { filename ->
112
async(Dispatchers.IO) {
113
File(filename).readText()
114
}
115
}.awaitAll()
116
117
suspend fun performDatabaseOperation(): String = withContext(Dispatchers.IO) {
118
// Blocking database call
119
Thread.sleep(1000) // Simulated blocking I/O
120
"Database result"
121
}
122
123
// Custom limited parallelism dispatcher
124
val customIODispatcher = Dispatchers.IO.limitedParallelism(10)
125
126
suspend fun limitedIOOperation(): String = withContext(customIODispatcher) {
127
// Limited to 10 concurrent operations
128
performBlockingOperation()
129
}
130
```
131
132
### Dispatchers.Main
133
134
Dispatcher for operations that must run on the main/UI thread, typically used in Android and desktop applications.
135
136
```kotlin { .api }
137
val Dispatchers.Main: MainCoroutineDispatcher
138
139
interface MainCoroutineDispatcher : CoroutineDispatcher {
140
/** Immediate dispatcher that executes in place when already on main thread */
141
val immediate: MainCoroutineDispatcher
142
}
143
```
144
145
**Usage Examples:**
146
147
```kotlin
148
import kotlinx.coroutines.*
149
150
// Android/UI example
151
class MainActivity {
152
fun loadData() {
153
GlobalScope.launch {
154
// Background thread
155
val data = withContext(Dispatchers.IO) {
156
fetchDataFromNetwork()
157
}
158
159
// Switch to main thread for UI updates
160
withContext(Dispatchers.Main) {
161
updateUI(data)
162
}
163
}
164
}
165
166
// Using Main.immediate for performance
167
fun updateUI() {
168
GlobalScope.launch(Dispatchers.Main.immediate) {
169
// Executes immediately if already on main thread
170
textView.text = "Updated"
171
}
172
}
173
}
174
```
175
176
### Dispatchers.Unconfined
177
178
Unconfined dispatcher that starts coroutine execution in the caller thread but may resume in any thread after suspension.
179
180
```kotlin { .api }
181
val Dispatchers.Unconfined: CoroutineDispatcher
182
```
183
184
**Usage Examples:**
185
186
```kotlin
187
import kotlinx.coroutines.*
188
189
fun main() = runBlocking {
190
println("Main thread: ${Thread.currentThread().name}")
191
192
launch(Dispatchers.Unconfined) {
193
println("Start: ${Thread.currentThread().name}")
194
delay(100)
195
println("After delay: ${Thread.currentThread().name}") // May be different
196
delay(100)
197
println("After second delay: ${Thread.currentThread().name}")
198
}
199
200
delay(500)
201
}
202
```
203
204
### Custom Dispatchers
205
206
Creating custom dispatchers for specific use cases.
207
208
```kotlin { .api }
209
/** Creates dispatcher with limited parallelism */
210
fun CoroutineDispatcher.limitedParallelism(
211
parallelism: Int,
212
name: String? = null
213
): CoroutineDispatcher
214
215
/** Creates single-threaded dispatcher */
216
fun newSingleThreadContext(name: String): ExecutorCoroutineDispatcher
217
218
/** Creates fixed thread pool dispatcher */
219
fun newFixedThreadPoolContext(
220
nThreads: Int,
221
name: String
222
): ExecutorCoroutineDispatcher
223
```
224
225
**Usage Examples:**
226
227
```kotlin
228
import kotlinx.coroutines.*
229
import java.util.concurrent.Executors
230
231
// Limited parallelism dispatcher
232
val customDispatcher = Dispatchers.Default.limitedParallelism(4)
233
234
suspend fun limitedParallelOperation() = withContext(customDispatcher) {
235
// Limited to 4 concurrent operations
236
performOperation()
237
}
238
239
// Single thread dispatcher
240
val singleThreadDispatcher = newSingleThreadContext("SingleThread")
241
242
suspend fun serialOperation() = withContext(singleThreadDispatcher) {
243
// Always executes on the same thread
244
performSequentialOperation()
245
}
246
247
// Fixed thread pool
248
val fixedPoolDispatcher = newFixedThreadPoolContext(8, "FixedPool")
249
250
suspend fun poolOperation() = withContext(fixedPoolDispatcher) {
251
// Uses fixed pool of 8 threads
252
performPooledOperation()
253
}
254
255
// Remember to close custom dispatchers
256
fun cleanup() {
257
singleThreadDispatcher.close()
258
fixedPoolDispatcher.close()
259
}
260
```
261
262
### Dispatcher Configuration
263
264
System properties for configuring dispatcher behavior.
265
266
```kotlin { .api }
267
/** Property for IO dispatcher parallelism */
268
const val IO_PARALLELISM_PROPERTY_NAME: String = "kotlinx.coroutines.io.parallelism"
269
```
270
271
**Configuration Examples:**
272
273
```bash
274
# Set IO parallelism to 32 threads
275
java -Dkotlinx.coroutines.io.parallelism=32 MyApplication
276
277
# or programmatically
278
System.setProperty("kotlinx.coroutines.io.parallelism", "32")
279
```
280
281
### shutdown() Function
282
283
Shuts down all built-in dispatchers for clean application termination.
284
285
```kotlin { .api }
286
/**
287
* Shuts down built-in dispatchers and associated threads
288
* WARNING: Delicate API - makes coroutines framework inoperable
289
*/
290
@DelicateCoroutinesApi
291
fun Dispatchers.shutdown()
292
```
293
294
**Usage Example:**
295
296
```kotlin
297
import kotlinx.coroutines.*
298
299
fun shutdownApplication() {
300
// Complete all pending coroutines first
301
runBlocking {
302
// Wait for all work to complete
303
}
304
305
// Then shutdown dispatchers
306
Dispatchers.shutdown()
307
}
308
```
309
310
## Types
311
312
### CoroutineDispatcher
313
314
Base class for all coroutine dispatchers.
315
316
```kotlin { .api }
317
abstract class CoroutineDispatcher : AbstractCoroutineContextElement(ContinuationInterceptor) {
318
/** Dispatches execution of a runnable block */
319
abstract fun dispatch(context: CoroutineContext, block: Runnable)
320
321
/** Creates a view with limited parallelism */
322
open fun limitedParallelism(
323
parallelism: Int,
324
name: String? = null
325
): CoroutineDispatcher
326
}
327
```
328
329
### ExecutorCoroutineDispatcher
330
331
Dispatcher based on Java Executor.
332
333
```kotlin { .api }
334
abstract class ExecutorCoroutineDispatcher : CoroutineDispatcher(), Closeable {
335
/** The underlying executor */
336
abstract val executor: Executor
337
338
/** Closes the dispatcher and shuts down executor if owned */
339
abstract override fun close()
340
}
341
```