blob: 10081ef209a77db3df36d8e47da12bffb09cd510 [file] [log] [blame]
Roman Elizarovf16fd272017-02-07 11:26:00 +03001/*
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
Roman Elizarov3754f952017-01-18 20:47:54 +030017package kotlinx.coroutines.experimental
18
Roman Elizarovaa461cf2018-04-11 13:20:29 +030019import kotlinx.coroutines.experimental.timeunit.TimeUnit
Roman Elizarov1a016bd2017-07-12 11:41:34 +030020import java.util.concurrent.*
Roman Elizarov3754f952017-01-18 20:47:54 +030021import java.util.concurrent.atomic.AtomicInteger
Roman Elizarovea4a51b2017-01-31 12:01:25 +030022import kotlin.coroutines.experimental.CoroutineContext
Roman Elizarov3754f952017-01-18 20:47:54 +030023
24/**
Roman Elizaroved7b8642017-01-19 11:22:28 +030025 * Represents common pool of shared threads as coroutine dispatcher for compute-intensive tasks.
Nikolay Metchevc1c380c2018-02-11 13:13:08 +000026 *
27 * If there isn't a SecurityManager present it uses [java.util.concurrent.ForkJoinPool] when available, which implements
28 * efficient work-stealing algorithm for its queues, so every coroutine resumption is dispatched as a separate task even
29 * when it already executes inside the pool. When available, it wraps `ForkJoinPool.commonPool` and provides a similar
30 * shared pool where not.
31 *
32 * If there is a SecurityManager present (as would be if running inside a Java Web Start context) then a plain thread
33 * pool is created. This is to work around the fact that ForkJoinPool creates threads that cannot perform
34 * privileged actions.
Roman Elizarov3754f952017-01-18 20:47:54 +030035 */
Roman Elizarov67891d82017-01-23 16:47:20 +030036object CommonPool : CoroutineDispatcher() {
Roman Elizarov731f0ad2017-02-22 20:48:45 +030037 private var usePrivatePool = false
38
39 @Volatile
Roman Elizarov1a016bd2017-07-12 11:41:34 +030040 private var _pool: Executor? = null
Roman Elizarov3754f952017-01-18 20:47:54 +030041
42 private inline fun <T> Try(block: () -> T) = try { block() } catch (e: Throwable) { null }
43
Roman Elizarov731f0ad2017-02-22 20:48:45 +030044 private fun createPool(): ExecutorService {
Nikolay Metchevc1c380c2018-02-11 13:13:08 +000045 if (System.getSecurityManager() != null) return createPlainPool()
Roman Elizarov3754f952017-01-18 20:47:54 +030046 val fjpClass = Try { Class.forName("java.util.concurrent.ForkJoinPool") }
47 ?: return createPlainPool()
Roman Elizarov731f0ad2017-02-22 20:48:45 +030048 if (!usePrivatePool) {
49 Try { fjpClass.getMethod("commonPool")?.invoke(null) as? ExecutorService }
50 ?.let { return it }
51 }
Roman Elizarov7cf452e2017-01-29 21:58:33 +030052 Try { fjpClass.getConstructor(Int::class.java).newInstance(defaultParallelism()) as? ExecutorService }
Roman Elizarov3754f952017-01-18 20:47:54 +030053 ?. let { return it }
54 return createPlainPool()
55 }
56
Roman Elizarov7cf452e2017-01-29 21:58:33 +030057 private fun createPlainPool(): ExecutorService {
Roman Elizarov3754f952017-01-18 20:47:54 +030058 val threadId = AtomicInteger()
59 return Executors.newFixedThreadPool(defaultParallelism()) {
60 Thread(it, "CommonPool-worker-${threadId.incrementAndGet()}").apply { isDaemon = true }
61 }
62 }
63
64 private fun defaultParallelism() = (Runtime.getRuntime().availableProcessors() - 1).coerceAtLeast(1)
65
Roman Elizarov731f0ad2017-02-22 20:48:45 +030066 @Synchronized
Roman Elizarov1a016bd2017-07-12 11:41:34 +030067 private fun getOrCreatePoolSync(): Executor =
Roman Elizarov731f0ad2017-02-22 20:48:45 +030068 _pool ?: createPool().also { _pool = it }
69
70 override fun dispatch(context: CoroutineContext, block: Runnable) =
Roman Elizarov35d2c342017-07-20 14:54:39 +030071 try { (_pool ?: getOrCreatePoolSync()).execute(timeSource.trackTask(block)) }
72 catch (e: RejectedExecutionException) {
73 timeSource.unTrackTask()
74 DefaultExecutor.execute(block)
75 }
Roman Elizarov731f0ad2017-02-22 20:48:45 +030076
77 // used for tests
78 @Synchronized
79 internal fun usePrivatePool() {
Roman Elizarov1a016bd2017-07-12 11:41:34 +030080 shutdown(0)
Roman Elizarov731f0ad2017-02-22 20:48:45 +030081 usePrivatePool = true
Roman Elizarov1a016bd2017-07-12 11:41:34 +030082 _pool = null
Roman Elizarov731f0ad2017-02-22 20:48:45 +030083 }
84
85 // used for tests
86 @Synchronized
Roman Elizarov1a016bd2017-07-12 11:41:34 +030087 internal fun shutdown(timeout: Long) {
88 (_pool as? ExecutorService)?.apply {
Roman Elizarov731f0ad2017-02-22 20:48:45 +030089 shutdown()
90 if (timeout > 0)
91 awaitTermination(timeout, TimeUnit.MILLISECONDS)
Roman Elizarov35d2c342017-07-20 14:54:39 +030092 shutdownNow().forEach { DefaultExecutor.execute(it) }
Roman Elizarov731f0ad2017-02-22 20:48:45 +030093 }
Roman Elizarov1a016bd2017-07-12 11:41:34 +030094 _pool = Executor { throw RejectedExecutionException("CommonPool was shutdown") }
95 }
96
97 // used for tests
98 @Synchronized
99 internal fun restore() {
100 shutdown(0)
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300101 usePrivatePool = false
Roman Elizarov1a016bd2017-07-12 11:41:34 +0300102 _pool = null
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300103 }
Roman Elizarovdc9fd1c2017-04-07 10:35:28 +0300104
105 override fun toString(): String = "CommonPool"
Roman Elizarov3754f952017-01-18 20:47:54 +0300106}