1 package benchmarks
2 
3 import benchmarks.akka.CORES_COUNT
4 import kotlinx.coroutines.*
5 import kotlinx.coroutines.scheduling.*
6 import org.openjdk.jmh.annotations.Param
7 import org.openjdk.jmh.annotations.Setup
8 import org.openjdk.jmh.annotations.TearDown
9 import java.io.Closeable
10 import java.util.concurrent.*
11 import kotlin.coroutines.CoroutineContext
12 
13 /**
14  * Base class to use different [CoroutineContext] in benchmarks via [Param] in inheritors.
15  * Currently allowed values are "fjp" for [CommonPool] and ftp_n for [ThreadPoolDispatcher] with n threads.
16  */
17 abstract class ParametrizedDispatcherBase : CoroutineScope {
18 
19     abstract var dispatcher: String
20     override lateinit var coroutineContext: CoroutineContext
21     private var closeable: Closeable? = null
22 
23     @Setup
setupnull24     open fun setup() {
25         coroutineContext = when {
26             dispatcher == "fjp" -> ForkJoinPool.commonPool().asCoroutineDispatcher()
27             dispatcher == "scheduler" -> {
28                 Dispatchers.Default
29             }
30             dispatcher.startsWith("ftp") -> {
31                 newFixedThreadPoolContext(dispatcher.substring(4).toInt(), dispatcher).also { closeable = it }
32             }
33             else -> error("Unexpected dispatcher: $dispatcher")
34         }
35     }
36 
37     @TearDown
tearDownnull38     fun tearDown() {
39         closeable?.close()
40     }
41 
42 }
43