public static class Job.DefaultImpls
A background job. Conceptually, a job is a cancellable thing with a simple life-cycle that
culminates in its completion. Jobs can be arranged into parent-child hierarchies where cancellation
or completion of parent immediately cancels all its Job.getChildren
.
The most basic instances of interface Job
are created with BuildersKt.launch
coroutine builder or with a
Job()
factory function. Other coroutine builders and primitives like
interface Deferred
also implement interface Job
interface.
A job has the following states:
| State | Job.isActive
| Job.isCompleted
| Job.isCancelled
|
| --------------------------------------- | ---------- | ------------- | ------------- |
| New (optional initial state) | false
| false
| false
|
| Active (default initial state) | true
| false
| false
|
| Completing (optional transient state) | true
| false
| false
|
| Cancelling (optional transient state) | false
| false
| true
|
| Cancelled (final state) | false
| true
| true
|
| Completed (final state) | false
| true
| false
|
Usually, a job is created in active state (it is created and started). However, coroutine builders
that provide an optional start
parameter create a coroutine in new state when this parameter is set to
CoroutineStart.LAZY. Such a job can be made active by invoking Job.start
or Job.join
.
A job can be cancelled at any time with Job.cancel
function that forces it to transition to
cancelling state immediately. Job that is not backed by a coroutine (see Job()
function) and does not have
Job.getChildren
becomes cancelled on Job.cancel
immediately.
Otherwise, job becomes cancelled when it finishes executing its code and
when all its children Job.isCompleted
.
wait children
+-----+ start +--------+ complete +-------------+ finish +-----------+
| New | ---------------> | Active | -----------> | Completing | -------> | Completed |
+-----+ +--------+ +-------------+ +-----------+
| | |
| cancel | cancel | cancel
V V |
+-----------+ finish +------------+ |
| Cancelled | <--------- | Cancelling | <----------------+
|(completed)| +------------+
+-----------+
A job in the coroutineContext represents the coroutine itself. A job is active while the coroutine is working and job's cancellation aborts the coroutine when the coroutine is suspended on a cancellable suspension point by throwing CancellationException.
A job can have a parent job. A job with a parent is cancelled when its parent is cancelled or completes exceptionally. Parent job waits for all its children to complete in completing or cancelling state. Completing state is purely internal to the job. For an outside observer a completing job is still active, while internally it is waiting for its children.
All functions on this interface and on all interfaces derived from it are thread-safe and can be safely invoked from concurrent coroutines without external synchronization.