• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 @file:JvmMultifileClass
6 @file:JvmName("ThreadPoolDispatcherKt")
7 package kotlinx.coroutines
8 
9 import java.util.concurrent.*
10 import java.util.concurrent.atomic.AtomicInteger
11 
12 /**
13  * Creates a coroutine execution context with the fixed-size thread-pool and built-in [yield] support.
14  * **NOTE: The resulting [ExecutorCoroutineDispatcher] owns native resources (its threads).
15  * Resources are reclaimed by [ExecutorCoroutineDispatcher.close].**
16  *
17  * If the resulting dispatcher is [closed][ExecutorCoroutineDispatcher.close] and
18  * attempt to submit a continuation task is made,
19  * then the [Job] of the affected task is [cancelled][Job.cancel] and the task is submitted to the
20  * [Dispatchers.IO], so that the affected coroutine can cleanup its resources and promptly complete.
21  *
22  * This is a **delicate** API. The result of this method is a closeable resource with the
23  * associated native resources (threads). It should not be allocated in place,
24  * should be closed at the end of its lifecycle, and has non-trivial memory and CPU footprint.
25  * If you do not need a separate thread-pool, but only have to limit effective parallelism of the dispatcher,
26  * it is recommended to use [CoroutineDispatcher.limitedParallelism] instead.
27  *
28  * If you need a completely separate thread-pool with scheduling policy that is based on the standard
29  * JDK executors, use the following expression:
30  * `Executors.newFixedThreadPool().asCoroutineDispatcher()`.
31  * See [Executor.asCoroutineDispatcher] for details.
32  *
33  * @param nThreads the number of threads.
34  * @param name the base name of the created threads.
35  */
36 @DelicateCoroutinesApi
37 public actual fun newFixedThreadPoolContext(nThreads: Int, name: String): ExecutorCoroutineDispatcher {
38     require(nThreads >= 1) { "Expected at least one thread, but $nThreads specified" }
39     val threadNo = AtomicInteger()
40     val executor = Executors.newScheduledThreadPool(nThreads) { runnable ->
41         val t = Thread(runnable, if (nThreads == 1) name else name + "-" + threadNo.incrementAndGet())
42         t.isDaemon = true
43         t
44     }
45     return executor.asCoroutineDispatcher()
46 }
47