|
| 1 | +/* |
| 2 | + * Copyright 2016-2017 JetBrains s.r.o. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package kotlinx.coroutines.experimental |
| 18 | + |
| 19 | +import java.util.concurrent.Executor |
| 20 | +import java.util.concurrent.Executors |
| 21 | +import kotlin.coroutines.experimental.CoroutineContext |
| 22 | + |
| 23 | +/** |
| 24 | + * This is a common pool of shared threads for blocking tasks. |
| 25 | + * |
| 26 | + * It uses a *unbounded* cached thread pool. |
| 27 | + */ |
| 28 | +object BlockingPool : CoroutineDispatcher(), Executor { |
| 29 | + |
| 30 | + private val threadGroup = ThreadGroup("kotlinx.coroutines.BlockingPool") |
| 31 | + |
| 32 | + private val executor = Executors.newCachedThreadPool({ |
| 33 | + Thread(threadGroup, it, "kotlinx.coroutines.BlockingPool-${System.identityHashCode(it).toString(16)}").apply { |
| 34 | + isDaemon = true |
| 35 | + } |
| 36 | + }) |
| 37 | + |
| 38 | + override fun execute(command: Runnable) = executor.execute(command) |
| 39 | + |
| 40 | + override fun dispatch(context: CoroutineContext, block: Runnable) { |
| 41 | + execute(block) |
| 42 | + } |
| 43 | + |
| 44 | + fun isDispatchNeeded(): Boolean = threadGroup !== Thread.currentThread().threadGroup |
| 45 | + |
| 46 | + override fun isDispatchNeeded(context: CoroutineContext): Boolean = isDispatchNeeded() |
| 47 | +} |
0 commit comments