JVM-specific implementation of kotlinx.coroutines core library providing coroutine primitives, builders, dispatchers, and synchronization primitives for asynchronous programming in Kotlin.
—
Lifecycle management for coroutines providing hierarchical cancellation, completion tracking, and structured concurrency with parent-child relationships.
Represents a cancellable background job with a well-defined lifecycle and states.
interface Job : CoroutineContext.Element {
/** True if job is active and running */
val isActive: Boolean
/** True if job has completed (successfully or with failure) */
val isCompleted: Boolean
/** True if job was cancelled */
val isCancelled: Boolean
/** Sequence of all child jobs */
val children: Sequence<Job>
/** Starts the job if it was created in lazy state */
fun start(): Boolean
/** Cancels the job with optional cause */
fun cancel(cause: CancellationException? = null)
/** Suspends until job completion */
suspend fun join()
/** Select clause for join operation */
val onJoin: SelectClause0
/** Registers completion handler */
fun invokeOnCompletion(handler: CompletionHandler): DisposableHandle
/** Cancels job and suspends until completion */
suspend fun cancelAndJoin()
}
typealias CompletionHandler = (cause: Throwable?) -> UnitJob States:
| State | isActive | isCompleted | isCancelled |
|---|---|---|---|
| New (lazy) | false | false | false |
| Active | true | false | false |
| Completing | true | false | false |
| Cancelling | false | false | true |
| Cancelled | false | true | true |
| Completed | false | true | false |
Usage Examples:
import kotlinx.coroutines.*
fun main() = runBlocking {
// Basic job lifecycle
val job = launch {
repeat(5) { i ->
println("Working $i")
delay(500)
}
}
delay(1500) // Let it work for a while
println("Job state - Active: ${job.isActive}, Completed: ${job.isCompleted}")
job.cancel() // Cancel the job
job.join() // Wait for cancellation to complete
println("Job state - Active: ${job.isActive}, Cancelled: ${job.isCancelled}")
}
// Completion handler example
fun jobWithCompletionHandler() = runBlocking {
val job = launch {
try {
delay(1000)
println("Job completed normally")
} catch (e: CancellationException) {
println("Job was cancelled")
throw e
}
}
job.invokeOnCompletion { cause ->
if (cause != null) {
println("Job completed with exception: $cause")
} else {
println("Job completed successfully")
}
}
delay(500)
job.cancel()
job.join()
}A Job that produces a result value, created by async coroutine builder.
interface Deferred<out T> : Job {
/** Suspends until result is available and returns it */
suspend fun await(): T
/** Gets result if completed, throws if not completed or failed */
fun getCompleted(): T
/** Returns completion exception or null if completed successfully */
fun getCompletionExceptionOrNull(): Throwable?
/** Select clause for await operation */
val onAwait: SelectClause1<T>
}Usage Examples:
import kotlinx.coroutines.*
fun main() = runBlocking {
// Single deferred
val deferred = async {
delay(1000)
"Hello, World!"
}
val result = deferred.await()
println(result)
// Multiple concurrent operations
val deferredList = List(5) { i ->
async {
delay((i + 1) * 100L)
"Result $i"
}
}
val results = deferredList.awaitAll()
println("All results: $results")
// Error handling
val faultyDeferred = async {
delay(100)
throw RuntimeException("Something went wrong")
}
try {
faultyDeferred.await()
} catch (e: RuntimeException) {
println("Caught exception: ${e.message}")
}
}
// Getting completed result without suspending
fun checkCompletedResult() = runBlocking {
val deferred = async {
delay(100)
42
}
delay(200) // Ensure completion
if (deferred.isCompleted) {
val result = deferred.getCompleted()
println("Result: $result")
}
}A Job that can be completed manually, created with Job() factory function.
interface CompletableJob : Job {
/** Completes the job successfully */
fun complete(): Boolean
/** Completes the job with exception */
fun completeExceptionally(exception: Throwable): Boolean
}
/** Creates a new CompletableJob */
fun Job(parent: Job? = null): CompletableJobUsage Examples:
import kotlinx.coroutines.*
fun main() = runBlocking {
// Manual job completion
val job = Job()
launch {
job.join()
println("Job completed!")
}
delay(1000)
job.complete() // Manually complete the job
// CompletableJob with parent
val parentJob = Job()
val childJob = Job(parentJob)
launch {
childJob.join()
println("Child job completed")
}
launch {
parentJob.join()
println("Parent job completed")
}
childJob.complete()
parentJob.complete()
}
// Error completion example
fun errorCompletionExample() = runBlocking {
val job = Job()
launch {
try {
job.join()
println("Should not reach here")
} catch (e: Exception) {
println("Job failed with: ${e.message}")
}
}
delay(100)
job.completeExceptionally(RuntimeException("Manual failure"))
}A special job that doesn't cancel its parent when its children fail, enabling supervisor pattern for fault tolerance.
/** Creates a supervisor job that doesn't propagate child failures */
fun SupervisorJob(parent: Job? = null): CompletableJob
/** Creates a supervisor scope where child failures don't cancel siblings */
suspend fun <T> supervisorScope(
block: suspend CoroutineScope.() -> T
): TUsage Examples:
import kotlinx.coroutines.*
fun main() = runBlocking {
// SupervisorJob example
val supervisor = SupervisorJob()
launch(supervisor) {
launch {
delay(100)
throw RuntimeException("Child 1 failed")
}
launch {
delay(200)
println("Child 2 completed successfully")
}
launch {
delay(300)
println("Child 3 completed successfully")
}
}
delay(500)
supervisor.complete()
}
// supervisorScope example
suspend fun processItems(items: List<String>) = supervisorScope {
items.map { item ->
async {
if (item == "fail") {
throw RuntimeException("Failed to process $item")
}
"Processed $item"
}
}.mapNotNull { deferred ->
try {
deferred.await()
} catch (e: Exception) {
println("Item processing failed: ${e.message}")
null // Continue with other items
}
}
}Understanding parent-child relationships and cancellation propagation.
/** Extension property to get job from coroutine context */
val CoroutineContext.job: Job
/** Extension property to check if context is active */
val CoroutineContext.isActive: Boolean
/** Ensures the context is active, throws CancellationException if cancelled */
fun CoroutineContext.ensureActive()
/** Cancellation exception for cooperative cancellation */
class CancellationException(
message: String? = null,
cause: Throwable? = null
) : IllegalStateException(message, cause)Usage Examples:
import kotlinx.coroutines.*
fun main() = runBlocking {
// Parent-child cancellation
val parentJob = launch {
val child1 = launch {
try {
repeat(10) { i ->
delay(100)
println("Child 1: $i")
}
} catch (e: CancellationException) {
println("Child 1 cancelled")
throw e
}
}
val child2 = launch {
try {
repeat(10) { i ->
delay(150)
println("Child 2: $i")
}
} catch (e: CancellationException) {
println("Child 2 cancelled")
throw e
}
}
delay(500)
println("Parent completing")
}
delay(300)
parentJob.cancel() // Cancels all children too
parentJob.join()
}
// Cooperative cancellation
suspend fun cooperativeCancellation() {
repeat(1000) { i ->
// Check for cancellation
if (!coroutineContext.isActive) {
println("Detected cancellation at iteration $i")
return
}
// Or use ensureActive() which throws CancellationException
coroutineContext.ensureActive()
// Simulate work
Thread.sleep(10)
}
}Handle for cleanup operations that can be disposed.
interface DisposableHandle {
/** Disposes of the resource */
fun dispose()
}Types used for select expressions in coroutine operations.
/** Base interface for select clauses */
sealed interface SelectClause
/** Select clause without parameters that doesn't select any value */
sealed interface SelectClause0 : SelectClause
/** Select clause without parameters that selects value of type T */
sealed interface SelectClause1<out T> : SelectClause
/** Select clause with parameter P that selects value of type Q */
sealed interface SelectClause2<in P, out Q> : SelectClauseJob-related context elements for coroutine management.
/** Context element key for Job */
object Job : CoroutineContext.Key<Job>
/** Creates a new job context element */
fun Job(): CompletableJobInstall with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlinx--kotlinx-coroutines-core-jvm