PHondogo
08/01/2024, 9:31 PMPHondogo
08/01/2024, 9:31 PMval pool = Executors.newSingleThreadExecutor { runnable -> Thread(runnable, "The1") }
val pool2 = Executors.newSingleThreadExecutor { runnable -> Thread(runnable, "The2") }
suspend fun main() {
println("1 " + Thread.currentThread().name) // main
withContext(pool.asCoroutineDispatcher()) {
println("2 " + Thread.currentThread().name) // The1
}
println("3 " + Thread.currentThread().name) // The1 ?? Why not main ??
withContext(pool2.asCoroutineDispatcher()) {
println("4 " + Thread.currentThread().name) // The2
}
println("5 " + Thread.currentThread().name) // The2 ?? Why not main ??
pool.shutdownNow()
pool2.shutdownNow()
}
Chris Lee
08/01/2024, 11:34 PMwithContext
to dispatch to, hence it resumes directly in the invoking thread (the thread running the withContext
block). You can change the behaviour by wrapping everything in withContext(Dispatchers.Default)
, for example, or any other dispatcher of your choosing.
withContext
uses suspendCoroutineUninterceptedOrReturn
which is documented as:
Invocation of Continuation.resumeWith resumes coroutine directly in the invoker’s thread without going through the ContinuationInterceptor that might be present in the coroutine’s CoroutineContext. It is the invoker’s responsibility to ensure that a proper invocation context is established. Continuation.intercepted can be used to acquire the intercepted continuation.…`resumeWith` in the code path is called only when there is no dispatcher, otherwise it submits the continuation to the last dispatcher.
streetsofboston
08/02/2024, 2:03 AM