Coroutines always execute in some context represented by a value of the CoroutineContext type, defined in the Kotlin standard library.
The coroutine context is a set of various elements. The main elements are the Job of the coroutine, which we’ve seen before, and its dispatcher, which is covered in this section.
The coroutine context includes a coroutine dispatcher that determines what thread or threads the corresponding coroutine uses for its execution. The coroutine dispatcher can confine coroutine execution to a specific thread, dispatch it to a thread pool, or let it run unconfined.
It is declared as base class to be extended by all coroutine dispatcher implementations.
Coroutine Dispatcher's code
(Actually, this below code and java doc has a many information. The contents to be discussed below are described, I think read this is very useful to additional understanding.)
java doc
Base class to be extended by all coroutine dispatcher implementations.
The following standard implementations are provided by kotlinx.coroutines as properties on the [Dispatchers] object:
[Dispatchers.Default] is used by all standard builders if no dispatcher or any other [ContinuationInterceptor] is specified in their context. It uses a common pool of shared background threads.
This is an appropriate choice for compute-intensive coroutines that consume CPU resources.
[Dispatchers.IO] : uses a shared pool of on-demand created threads and is designed for offloading of IO-intensive _blocking_ operations (like file I/O and blocking socket I/O).
[Dispatchers.Unconfined] — starts coroutine execution in the current call-frame until the first suspension, where upon the coroutine builder function returns. The coroutine will later resume in whatever thread used by the corresponding suspending function, without confining it to any specific thread or pool. The Unconfined dispatcher should not normally be used in code**.
Private thread pools can be created with [newSingleThreadContext] and [newFixedThreadPoolContext].
An arbitrary [Executor][java.util.concurrent.Executor] can be converted to a dispatcher with the [asCoroutineDispatcher] extension function.
This class ensures that debugging facilities in [newCoroutineContext] function work properly.
code
Try the below example
It produces the following output (maybe in different order):
When launch { ... } is used without parameters, it inherits the context (and thus dispatcher) from the CoroutineScope it is being launched from. In this case, it inherits the context of the main runBlocking coroutine which runs in the main thread.
Dispatchers.Unconfined is a special dispatcher that also appears to run in the main thread, but it is, in fact, a different mechanism that is explained later.
The default dispatcher is used when no other dispatcher is explicitly specified in the scope. It is represented by Dispatchers.Default and uses a shared background pool of threads.
newSingleThreadContext creates a thread for the coroutine to run. A dedicated thread is a very expensive resource. In a real application it must be either released, when no longer needed, using the close function, or stored in a top-level variable and reused throughout the application.
Unconfined vs confined dispatcher
The Dispatchers.Unconfined coroutine dispatcher starts a coroutine in the caller thread, but only until the first suspension point. The unconfined dispatcher is appropriate for coroutines which neither consume CPU time nor update any shared data confined to a specific thread.
On the other side, the dispatcher is inherited from the outer CoroutineScope by default. The default dispatcher for the runBlocking coroutine, in particular, is confined to the invoker thread, so inheriting it has the effect of confining execution to this thread with predictable FIFO scheduling.
Produces the output:
So, the coroutine with the context inherited from runBlocking {...} continues to execute in the main thread, while the unconfined one resumes in the default executor thread that the delay function is using.
The unconfined dispatcher is an advanced mechanism that can be helpful in certain corner cases where dispatching of a coroutine for its execution later is not needed or produces undesirable side-effects, because some operation in a coroutine must be performed right away. The unconfined dispatcher should not be used in general code.
Debugging coroutines and threads
Coroutines can suspend on one thread and resume on another thread. Even with a single-threaded dispatcher it might be hard to figure out what the coroutine was doing, where, and when if you don’t have special tooling.
Debugging with IDEA
The Coroutine Debugger of the Kotlin plugin simplifies debugging coroutines in IntelliJ IDEA.
Debugging works for versions 1.3.8 or later of kotlinx-coroutines-core.
The Debug tool window contains the Coroutines tab. In this tab, you can find information about both currently running and suspended coroutines. The coroutines are grouped by the dispatcher they are running on.
With the coroutine debugger, you can:
Check the state of each coroutine.
See the values of local and captured variables for both running and suspended coroutines.
See a full coroutine creation stack, as well as a call stack inside the coroutine. The stack includes all frames with variable values, even those that would be lost during standard debugging.
Get a full report that contains the state of each coroutine and its stack. To obtain it, right-click inside the Coroutines tab, and then click Get Coroutines Dump.
To start coroutine debugging, you just need to set breakpoints and run the application in debug mode.
Run the following code with the -Dkotlinx.coroutines.debug JVM option (see debug):
It demonstrates several new techniques. One is using runBlocking with an explicitly specified context, and the other one is using the withContext function to change the context of a coroutine while still staying in the same coroutine, as you can see in the output below:
Note that this example also uses the use function from the Kotlin standard library to release threads created with newSingleThreadContext when they are no longer needed.
Chilren of a coroutine
When a coroutine is launched in the CoroutineScope of another coroutine, it inherits its context via CoroutineScope.coroutineContext and the Job of the new coroutine becomes a child of the parent coroutine’s job. When the parent coroutine is cancelled, all its children are recursively cancelled, too.
However, this parent-child relation can be explictly overriden in one of two ways:
When a different scope is explicitly specified when launching a coroutine (for example, GlobalScope.launch), then is does no inherit a Job from the parent scope.
When a different Job object is passed as the context for the new coroutine (as shown in the example below), then is overrides the Job of the parent scope.
In both cases, the launched coroutine is not tied to the scope it was launched fron and operates independently.
Combining context elements
Sometimes we need to define multiple elements for a coroutine context. We can use the + operator for that. For example, we can launch a coroutine with an explicitly specified dispatcher and an explicitly specified name at the same time:
The output of this code with the -Dkotlinx.coroutines.debug JVM option is:
Thread-local data
Sometimes it is convenient to have an ability to pass some thread-local data to or between coroutines. However, since they are not bound to any particular thread, this will likely lead to boilerplate if done manually.
For ThreadLocal, the asContextElement extension function is here for the rescue. It creates an additional context element which keeps the value of the given ThreadLocal and restores it every time the coroutine switches its context.
In this example we launch a new coroutine in a background thread pool using Dispatchers.Default, so it works on a different thread from the thread pool, but it still has the value of the thread local variable that we specified using threadLocal.asContextElement(value = “launch”), no matter which thread the coroutine is executed on. Thus, the output (with debug) is:
It’s easy to forget to set the corresponding context element. The thread-local variable accessed from the coroutine may then have an unexpected value, if the thread running the coroutine is different. To avoid such situations, it is recommended to use the ensurePresent method and fail-fast on improper usages.
ThreadLocal has first-class support and can be used with any primitive kotlinx.coroutines provides. It has one key limitation, though: when a thread-local is mutated, a new value is not propagated to the coroutine caller (because a context element cannot track all ThreadLocal object accesses), and the updated value is lost on the next suspension. Use withContext to update the value of the thread-local in a coroutine, see asContextElement for more details.
Alternatively, a value can be stored in a mutable box like class Counter(var i: Int), which is, in turn, stored in a thread-local variable. However, in this case you are fully responsible to synchronize potentially concurrent modifications to the variable in this mutable box.
For advanced usage, for example for integration with logging MDC, transactional contexts or any other libraries which internally use thread-locals for passing data, see the documentation of the ThreadContextElement interface that should be implemented.