aboutsummaryrefslogtreecommitdiff
path: root/kotlinx-coroutines-core/common/src/selects/SelectUnbiased.kt
blob: c33c5b1f2c0d0f2e5a97a80488895ec6c584af8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
 * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.coroutines.selects

import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*

/**
 * Waits for the result of multiple suspending functions simultaneously like [select], but in an _unbiased_
 * way when multiple clauses are selectable at the same time.
 *
 * This unbiased implementation of `select` expression randomly shuffles the clauses before checking
 * if they are selectable, thus ensuring that there is no statistical bias to the selection of the first
 * clauses.
 *
 * See [select] function description for all the other details.
 */
public suspend inline fun <R> selectUnbiased(crossinline builder: SelectBuilder<R>.() -> Unit): R =
    suspendCoroutineUninterceptedOrReturn { uCont ->
        val scope = UnbiasedSelectBuilderImpl(uCont)
        try {
            builder(scope)
        } catch (e: Throwable) {
            scope.handleBuilderException(e)
        }
        scope.initSelectResult()
    }


@PublishedApi
internal class UnbiasedSelectBuilderImpl<in R>(uCont: Continuation<R>) :
    SelectBuilder<R> {
    val instance = SelectBuilderImpl(uCont)
    val clauses = arrayListOf<() -> Unit>()

    @PublishedApi
    internal fun handleBuilderException(e: Throwable): Unit = instance.handleBuilderException(e)

    @PublishedApi
    internal fun initSelectResult(): Any? {
        if (!instance.isSelected) {
            try {
                clauses.shuffle()
                clauses.forEach { it.invoke() }
            } catch (e: Throwable) {
                instance.handleBuilderException(e)
            }
        }
        return instance.getResult()
    }

    override fun SelectClause0.invoke(block: suspend () -> R) {
        clauses += { registerSelectClause0(instance, block) }
    }

    override fun <Q> SelectClause1<Q>.invoke(block: suspend (Q) -> R) {
        clauses += { registerSelectClause1(instance, block) }
    }

    override fun <P, Q> SelectClause2<P, Q>.invoke(param: P, block: suspend (Q) -> R) {
        clauses += { registerSelectClause2(instance, param, block) }
    }

    override fun onTimeout(timeMillis: Long, block: suspend () -> R) {
        clauses += { instance.onTimeout(timeMillis, block) }
    }
}