Shut down the underlying Executor of ExecutorCoroutineDispatcher

纵饮孤独 提交于 2019-12-11 01:46:09

问题


I repeatedly find myself writing code as this:

val threadPoolExecutor = Executors.newCachedThreadPool()
val threadPool = threadPool.asCoroutineDispatcher()

What I really need is just the coroutine dispatcher so I can write stuff like

launch(threadPool) { ... }

or

withContext(threadPool) { ... }

and I need the threadPoolExecutor just to be able to shut it down on cleanup. Is there a way to use the coroutine dispatcher instance to shut it down instead?


回答1:


At the moment this is no out-of-the box solution, but you can write your own asCoroutineDispatcher extension to provide such an experience:

abstract class CloseableCoroutineDispatcher : CoroutineDispatcher(), Closeable

fun ExecutorService.asCoroutineDispatcher(): CloseableCoroutineDispatcher =
    object : CloseableCoroutineDispatcher() {
        val delegate = (this@asCoroutineDispatcher as Executor).asCoroutineDispatcher()
        override fun isDispatchNeeded(context: CoroutineContext): Boolean = delegate.isDispatchNeeded(context)
        override fun dispatch(context: CoroutineContext, block: Runnable) = delegate.dispatch(context, block)
        override fun close() = shutdown()
    }

This question had lead to the following change request: https://github.com/Kotlin/kotlinx.coroutines/issues/278



来源:https://stackoverflow.com/questions/49217668/shut-down-the-underlying-executor-of-executorcoroutinedispatcher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!