Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 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 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 17 | package kotlinx.coroutines.experimental |
| 18 | |
Roman Elizarov | aa461cf | 2018-04-11 13:20:29 +0300 | [diff] [blame] | 19 | import kotlinx.coroutines.experimental.timeunit.TimeUnit |
Roman Elizarov | 1a016bd | 2017-07-12 11:41:34 +0300 | [diff] [blame] | 20 | import java.util.concurrent.* |
Vsevolod Tolstopyatov | 87f2faa | 2018-04-30 22:53:02 +0300 | [diff] [blame] | 21 | import java.util.concurrent.atomic.* |
| 22 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 23 | |
| 24 | /** |
Roman Elizarov | ed7b864 | 2017-01-19 11:22:28 +0300 | [diff] [blame] | 25 | * Represents common pool of shared threads as coroutine dispatcher for compute-intensive tasks. |
Nikolay Metchev | c1c380c | 2018-02-11 13:13:08 +0000 | [diff] [blame] | 26 | * |
| 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 Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 35 | */ |
Roman Elizarov | 67891d8 | 2017-01-23 16:47:20 +0300 | [diff] [blame] | 36 | object CommonPool : CoroutineDispatcher() { |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 37 | |
| 38 | /** |
| 39 | * Name of the property that controls default parallelism level of [CommonPool]. |
| 40 | * If the property is not specified, `Runtime.getRuntime().availableProcessors() - 1` will be used instead (or `1` for single-core JVM). |
| 41 | * Note that until Java 10, if an application is run within a container, |
paolop | e06b6ca | 2018-06-09 09:48:44 +0000 | [diff] [blame] | 42 | * `Runtime.getRuntime().availableProcessors()` is not aware of container constraints and will return the real number of cores. |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 43 | */ |
| 44 | public const val DEFAULT_PARALLELISM_PROPERTY_NAME = "kotlinx.coroutines.default.parallelism" |
| 45 | |
| 46 | private val parallelism = run<Int> { |
| 47 | val property = Try { System.getProperty(DEFAULT_PARALLELISM_PROPERTY_NAME) } |
| 48 | if (property == null) { |
| 49 | (Runtime.getRuntime().availableProcessors() - 1).coerceAtLeast(1) |
| 50 | } else { |
| 51 | val parallelism = property.toIntOrNull() |
| 52 | if (parallelism == null || parallelism < 1) { |
| 53 | error("Expected positive number in $DEFAULT_PARALLELISM_PROPERTY_NAME, but has $property") |
| 54 | } |
| 55 | parallelism |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // For debug and tests |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 60 | private var usePrivatePool = false |
| 61 | |
| 62 | @Volatile |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 63 | private var pool: Executor? = null |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 64 | |
| 65 | private inline fun <T> Try(block: () -> T) = try { block() } catch (e: Throwable) { null } |
| 66 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 67 | private fun createPool(): ExecutorService { |
Nikolay Metchev | c1c380c | 2018-02-11 13:13:08 +0000 | [diff] [blame] | 68 | if (System.getSecurityManager() != null) return createPlainPool() |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 69 | val fjpClass = Try { Class.forName("java.util.concurrent.ForkJoinPool") } |
| 70 | ?: return createPlainPool() |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 71 | if (!usePrivatePool) { |
| 72 | Try { fjpClass.getMethod("commonPool")?.invoke(null) as? ExecutorService } |
| 73 | ?.let { return it } |
| 74 | } |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 75 | Try { fjpClass.getConstructor(Int::class.java).newInstance(parallelism) as? ExecutorService } |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 76 | ?. let { return it } |
| 77 | return createPlainPool() |
| 78 | } |
| 79 | |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 80 | private fun createPlainPool(): ExecutorService { |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 81 | val threadId = AtomicInteger() |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 82 | return Executors.newFixedThreadPool(parallelism) { |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 83 | Thread(it, "CommonPool-worker-${threadId.incrementAndGet()}").apply { isDaemon = true } |
| 84 | } |
| 85 | } |
| 86 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 87 | @Synchronized |
Roman Elizarov | 1a016bd | 2017-07-12 11:41:34 +0300 | [diff] [blame] | 88 | private fun getOrCreatePoolSync(): Executor = |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 89 | pool ?: createPool().also { pool = it } |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 90 | |
| 91 | override fun dispatch(context: CoroutineContext, block: Runnable) = |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 92 | try { (pool ?: getOrCreatePoolSync()).execute(timeSource.trackTask(block)) } |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 93 | catch (e: RejectedExecutionException) { |
| 94 | timeSource.unTrackTask() |
| 95 | DefaultExecutor.execute(block) |
| 96 | } |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 97 | |
| 98 | // used for tests |
| 99 | @Synchronized |
| 100 | internal fun usePrivatePool() { |
Roman Elizarov | 1a016bd | 2017-07-12 11:41:34 +0300 | [diff] [blame] | 101 | shutdown(0) |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 102 | usePrivatePool = true |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 103 | pool = null |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 104 | } |
| 105 | |
| 106 | // used for tests |
| 107 | @Synchronized |
Roman Elizarov | 1a016bd | 2017-07-12 11:41:34 +0300 | [diff] [blame] | 108 | internal fun shutdown(timeout: Long) { |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 109 | (pool as? ExecutorService)?.apply { |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 110 | shutdown() |
| 111 | if (timeout > 0) |
| 112 | awaitTermination(timeout, TimeUnit.MILLISECONDS) |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 113 | shutdownNow().forEach { DefaultExecutor.execute(it) } |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 114 | } |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 115 | pool = Executor { throw RejectedExecutionException("CommonPool was shutdown") } |
Roman Elizarov | 1a016bd | 2017-07-12 11:41:34 +0300 | [diff] [blame] | 116 | } |
| 117 | |
| 118 | // used for tests |
| 119 | @Synchronized |
| 120 | internal fun restore() { |
| 121 | shutdown(0) |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 122 | usePrivatePool = false |
Vsevolod Tolstopyatov | 6a0ce76 | 2018-05-22 19:47:50 +0300 | [diff] [blame] | 123 | pool = null |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 124 | } |
Roman Elizarov | dc9fd1c | 2017-04-07 10:35:28 +0300 | [diff] [blame] | 125 | |
| 126 | override fun toString(): String = "CommonPool" |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 127 | } |