blob: a151076ce979b4a5581ed668e7e8259bca193c16 [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.*
Vsevolod Tolstopyatov87f2faa2018-04-30 22:53:02 +030021import java.util.concurrent.atomic.*
22import kotlin.coroutines.experimental.*
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() {
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +030037
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,
paolope06b6ca2018-06-09 09:48:44 +000042 * `Runtime.getRuntime().availableProcessors()` is not aware of container constraints and will return the real number of cores.
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +030043 */
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 Elizarov731f0ad2017-02-22 20:48:45 +030060 private var usePrivatePool = false
61
62 @Volatile
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +030063 private var pool: Executor? = null
Roman Elizarov3754f952017-01-18 20:47:54 +030064
65 private inline fun <T> Try(block: () -> T) = try { block() } catch (e: Throwable) { null }
66
Roman Elizarov731f0ad2017-02-22 20:48:45 +030067 private fun createPool(): ExecutorService {
Nikolay Metchevc1c380c2018-02-11 13:13:08 +000068 if (System.getSecurityManager() != null) return createPlainPool()
Roman Elizarov3754f952017-01-18 20:47:54 +030069 val fjpClass = Try { Class.forName("java.util.concurrent.ForkJoinPool") }
70 ?: return createPlainPool()
Roman Elizarov731f0ad2017-02-22 20:48:45 +030071 if (!usePrivatePool) {
72 Try { fjpClass.getMethod("commonPool")?.invoke(null) as? ExecutorService }
73 ?.let { return it }
74 }
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +030075 Try { fjpClass.getConstructor(Int::class.java).newInstance(parallelism) as? ExecutorService }
Roman Elizarov3754f952017-01-18 20:47:54 +030076 ?. let { return it }
77 return createPlainPool()
78 }
79
Roman Elizarov7cf452e2017-01-29 21:58:33 +030080 private fun createPlainPool(): ExecutorService {
Roman Elizarov3754f952017-01-18 20:47:54 +030081 val threadId = AtomicInteger()
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +030082 return Executors.newFixedThreadPool(parallelism) {
Roman Elizarov3754f952017-01-18 20:47:54 +030083 Thread(it, "CommonPool-worker-${threadId.incrementAndGet()}").apply { isDaemon = true }
84 }
85 }
86
Roman Elizarov731f0ad2017-02-22 20:48:45 +030087 @Synchronized
Roman Elizarov1a016bd2017-07-12 11:41:34 +030088 private fun getOrCreatePoolSync(): Executor =
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +030089 pool ?: createPool().also { pool = it }
Roman Elizarov731f0ad2017-02-22 20:48:45 +030090
91 override fun dispatch(context: CoroutineContext, block: Runnable) =
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +030092 try { (pool ?: getOrCreatePoolSync()).execute(timeSource.trackTask(block)) }
Roman Elizarov35d2c342017-07-20 14:54:39 +030093 catch (e: RejectedExecutionException) {
94 timeSource.unTrackTask()
95 DefaultExecutor.execute(block)
96 }
Roman Elizarov731f0ad2017-02-22 20:48:45 +030097
98 // used for tests
99 @Synchronized
100 internal fun usePrivatePool() {
Roman Elizarov1a016bd2017-07-12 11:41:34 +0300101 shutdown(0)
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300102 usePrivatePool = true
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +0300103 pool = null
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300104 }
105
106 // used for tests
107 @Synchronized
Roman Elizarov1a016bd2017-07-12 11:41:34 +0300108 internal fun shutdown(timeout: Long) {
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +0300109 (pool as? ExecutorService)?.apply {
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300110 shutdown()
111 if (timeout > 0)
112 awaitTermination(timeout, TimeUnit.MILLISECONDS)
Roman Elizarov35d2c342017-07-20 14:54:39 +0300113 shutdownNow().forEach { DefaultExecutor.execute(it) }
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300114 }
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +0300115 pool = Executor { throw RejectedExecutionException("CommonPool was shutdown") }
Roman Elizarov1a016bd2017-07-12 11:41:34 +0300116 }
117
118 // used for tests
119 @Synchronized
120 internal fun restore() {
121 shutdown(0)
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300122 usePrivatePool = false
Vsevolod Tolstopyatov6a0ce762018-05-22 19:47:50 +0300123 pool = null
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300124 }
Roman Elizarovdc9fd1c2017-04-07 10:35:28 +0300125
126 override fun toString(): String = "CommonPool"
Roman Elizarov3754f952017-01-18 20:47:54 +0300127}