asCoroutineDispatcher

Converts an instance of Window to an implementation of CoroutineDispatcher.

Converts an instance of ExecutorService to an implementation of ExecutorCoroutineDispatcher.

Interaction with delay and time-based coroutines.

If the given ExecutorService is an instance of ScheduledExecutorService, then all time-related coroutine operations such as delay, withTimeout and time-based Flow operators will be scheduled on this executor using schedule method. If the corresponding coroutine is cancelled, ScheduledFuture.cancel will be invoked on the corresponding future.

If the given ExecutorService is an instance of ScheduledThreadPoolExecutor, then prior to any scheduling, remove on cancel policy will be set via ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy in order to reduce the memory pressure of cancelled coroutines.

If the executor service is neither of this types, the separate internal thread will be used to track the delay and time-related executions, but the coroutine itself will still be executed on top of the given executor.

Rejected execution

If the underlying executor throws RejectedExecutionException on attempt to submit a continuation task (it happens when closing the resulting dispatcher, on underlying executor shutdown, or when it uses limited queues), then the Job of the affected task is cancelled and the task is submitted to the Dispatchers.IO, so that the affected coroutine can cleanup its resources and promptly complete.


Converts an instance of Executor to an implementation of CoroutineDispatcher.

Interaction with delay and time-based coroutines.

If the given Executor is an instance of ScheduledExecutorService, then all time-related coroutine operations such as delay, withTimeout and time-based Flow operators will be scheduled on this executor using schedule method. If the corresponding coroutine is cancelled, ScheduledFuture.cancel will be invoked on the corresponding future.

If the given Executor is an instance of ScheduledThreadPoolExecutor, then prior to any scheduling, remove on cancel policy will be set via ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy in order to reduce the memory pressure of cancelled coroutines.

If the executor is neither of this types, the separate internal thread will be used to track the delay and time-related executions, but the coroutine itself will still be executed on top of the given executor.

Rejected execution

If the underlying executor throws RejectedExecutionException on attempt to submit a continuation task (it happens when closing the resulting dispatcher, on underlying executor shutdown, or when it uses limited queues), then the Job of the affected task is cancelled and the task is submitted to the Dispatchers.IO, so that the affected coroutine can cleanup its resources and promptly complete.