JVM-specific implementation of kotlinx.coroutines core library providing coroutine primitives, builders, dispatchers, and synchronization primitives for asynchronous programming in Kotlin.
—
Thread pool implementations providing different execution contexts for coroutines, with JVM-specific optimizations and configurable parallelism.
Central object providing access to various coroutine dispatcher implementations.
object Dispatchers {
/** Dispatcher for CPU-intensive tasks */
val Default: CoroutineDispatcher
/** Dispatcher for UI thread operations */
val Main: MainCoroutineDispatcher
/** Dispatcher for blocking I/O operations (JVM-specific) */
val IO: CoroutineDispatcher
/** Unconfined dispatcher that starts in caller context */
val Unconfined: CoroutineDispatcher
/** Shuts down built-in dispatchers (delicate API) */
@DelicateCoroutinesApi
fun shutdown()
}Usage Examples:
import kotlinx.coroutines.*
fun main() = runBlocking {
// Different dispatchers for different tasks
// CPU-intensive computation
val result1 = withContext(Dispatchers.Default) {
(1..1000000).sum()
}
// Blocking I/O operation
val result2 = withContext(Dispatchers.IO) {
java.io.File("data.txt").readText()
}
// Unconfined - starts in current context
withContext(Dispatchers.Unconfined) {
println("Current thread: ${Thread.currentThread().name}")
delay(100) // May resume on different thread
println("After delay: ${Thread.currentThread().name}")
}
}Optimized for CPU-intensive tasks, backed by a shared thread pool with parallelism equal to the number of CPU cores.
val Dispatchers.Default: CoroutineDispatcherUsage Examples:
import kotlinx.coroutines.*
suspend fun heavyComputation(): Long = withContext(Dispatchers.Default) {
// CPU-intensive task
(1..10_000_000).fold(0L) { acc, i -> acc + i * i }
}
fun main() = runBlocking {
val jobs = List(4) {
async(Dispatchers.Default) {
heavyComputation()
}
}
val results = jobs.awaitAll()
println("Results: $results")
}Optimized for blocking I/O operations with elastic thread pool that can grow as needed, with configurable parallelism.
val Dispatchers.IO: CoroutineDispatcher
/** Property name for configuring IO parallelism */
const val IO_PARALLELISM_PROPERTY_NAME: String = "kotlinx.coroutines.io.parallelism"Key Features:
limitedParallelism() for creating custom thread poolsUsage Examples:
import kotlinx.coroutines.*
import java.io.File
suspend fun readFiles(filenames: List<String>): List<String> =
filenames.map { filename ->
async(Dispatchers.IO) {
File(filename).readText()
}
}.awaitAll()
suspend fun performDatabaseOperation(): String = withContext(Dispatchers.IO) {
// Blocking database call
Thread.sleep(1000) // Simulated blocking I/O
"Database result"
}
// Custom limited parallelism dispatcher
val customIODispatcher = Dispatchers.IO.limitedParallelism(10)
suspend fun limitedIOOperation(): String = withContext(customIODispatcher) {
// Limited to 10 concurrent operations
performBlockingOperation()
}Dispatcher for operations that must run on the main/UI thread, typically used in Android and desktop applications.
val Dispatchers.Main: MainCoroutineDispatcher
interface MainCoroutineDispatcher : CoroutineDispatcher {
/** Immediate dispatcher that executes in place when already on main thread */
val immediate: MainCoroutineDispatcher
}Usage Examples:
import kotlinx.coroutines.*
// Android/UI example
class MainActivity {
fun loadData() {
GlobalScope.launch {
// Background thread
val data = withContext(Dispatchers.IO) {
fetchDataFromNetwork()
}
// Switch to main thread for UI updates
withContext(Dispatchers.Main) {
updateUI(data)
}
}
}
// Using Main.immediate for performance
fun updateUI() {
GlobalScope.launch(Dispatchers.Main.immediate) {
// Executes immediately if already on main thread
textView.text = "Updated"
}
}
}Unconfined dispatcher that starts coroutine execution in the caller thread but may resume in any thread after suspension.
val Dispatchers.Unconfined: CoroutineDispatcherUsage Examples:
import kotlinx.coroutines.*
fun main() = runBlocking {
println("Main thread: ${Thread.currentThread().name}")
launch(Dispatchers.Unconfined) {
println("Start: ${Thread.currentThread().name}")
delay(100)
println("After delay: ${Thread.currentThread().name}") // May be different
delay(100)
println("After second delay: ${Thread.currentThread().name}")
}
delay(500)
}Creating custom dispatchers for specific use cases.
/** Creates dispatcher with limited parallelism */
fun CoroutineDispatcher.limitedParallelism(
parallelism: Int,
name: String? = null
): CoroutineDispatcher
/** Creates single-threaded dispatcher */
fun newSingleThreadContext(name: String): ExecutorCoroutineDispatcher
/** Creates fixed thread pool dispatcher */
fun newFixedThreadPoolContext(
nThreads: Int,
name: String
): ExecutorCoroutineDispatcherUsage Examples:
import kotlinx.coroutines.*
import java.util.concurrent.Executors
// Limited parallelism dispatcher
val customDispatcher = Dispatchers.Default.limitedParallelism(4)
suspend fun limitedParallelOperation() = withContext(customDispatcher) {
// Limited to 4 concurrent operations
performOperation()
}
// Single thread dispatcher
val singleThreadDispatcher = newSingleThreadContext("SingleThread")
suspend fun serialOperation() = withContext(singleThreadDispatcher) {
// Always executes on the same thread
performSequentialOperation()
}
// Fixed thread pool
val fixedPoolDispatcher = newFixedThreadPoolContext(8, "FixedPool")
suspend fun poolOperation() = withContext(fixedPoolDispatcher) {
// Uses fixed pool of 8 threads
performPooledOperation()
}
// Remember to close custom dispatchers
fun cleanup() {
singleThreadDispatcher.close()
fixedPoolDispatcher.close()
}System properties for configuring dispatcher behavior.
/** Property for IO dispatcher parallelism */
const val IO_PARALLELISM_PROPERTY_NAME: String = "kotlinx.coroutines.io.parallelism"Configuration Examples:
# Set IO parallelism to 32 threads
java -Dkotlinx.coroutines.io.parallelism=32 MyApplication
# or programmatically
System.setProperty("kotlinx.coroutines.io.parallelism", "32")Shuts down all built-in dispatchers for clean application termination.
/**
* Shuts down built-in dispatchers and associated threads
* WARNING: Delicate API - makes coroutines framework inoperable
*/
@DelicateCoroutinesApi
fun Dispatchers.shutdown()Usage Example:
import kotlinx.coroutines.*
fun shutdownApplication() {
// Complete all pending coroutines first
runBlocking {
// Wait for all work to complete
}
// Then shutdown dispatchers
Dispatchers.shutdown()
}Base class for all coroutine dispatchers.
abstract class CoroutineDispatcher : AbstractCoroutineContextElement(ContinuationInterceptor) {
/** Dispatches execution of a runnable block */
abstract fun dispatch(context: CoroutineContext, block: Runnable)
/** Creates a view with limited parallelism */
open fun limitedParallelism(
parallelism: Int,
name: String? = null
): CoroutineDispatcher
}Dispatcher based on Java Executor.
abstract class ExecutorCoroutineDispatcher : CoroutineDispatcher(), Closeable {
/** The underlying executor */
abstract val executor: Executor
/** Closes the dispatcher and shuts down executor if owned */
abstract override fun close()
}Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlinx--kotlinx-coroutines-core-jvm