https://kotlinlang.org logo
#coroutines
Title
# coroutines
u

uli

02/23/2017, 9:09 AM
Hi All, i've been doing some timings, based on variations of the "Shared mutable state and concurrency" examples form the coroutine guide and saw surprising results. First, here is my code:
Copy code
val massive = 1_000_000
private suspend fun aMassiveRun(context: CoroutineContext = CommonPool, action: suspend () -> Unit) {
    val jobs = List(massive) {
        launch(context) {
            action()
        }
    }
    jobs.forEach { it.join() }
}

private object ThreadConfinement1: Callable<Int> {
    val counterContext = newSingleThreadContext("CounterContext")

    override fun call(): Int {
        var counter = 0
        runBlocking<Unit> {
            aMassiveRun(counterContext) {
                counter++
            }
        }
        return counter
    }
}

private object ThreadConfinement2: Callable<Int> {
    val counterContext = newSingleThreadContext("CounterContext")

    override fun call(): Int {
        var counter = 0
        runBlocking<Unit> {
            aMassiveRun {
                run(counterContext) {
                    counter++
                }
            }
        }
        return counter
    }
}
I time both callables 5 times to warm up hotspot and only take the last measurement. Both tests run all incrementation on a single thread but ThreadConfinement2 does the scheduling of the actual work in form the CommonPool. The timings measured are 3.5s for ThreadConfinement2 while ThreadConfinement1 takes 5.8s on my machine. Can anyone explain, why ThreadConfinement2 is faster? This came as a big surprise to me. Edit: Further measurements did not support these numbers. I now get more expected timings of 2.6s for ThreadConfinement1 and 4.3s for ThreadConfinement2. I guess my machine was just doing funny things in the background. Timing things correctly is never easy in a multitasking environment.
e

elizarov

02/23/2017, 9:47 AM
That makes sense and is straightforward to explain. I'll add the other approach to the thread confinement to the next revision of guide, too, as well as measurement results and the reasons behind them. I'll setup JMH b enchmarks around them to measure it all properly.
u

uli

02/23/2017, 12:50 PM
Cool. Thanks!
2 Views