So I want to traverse a read only (or frozen if yo...
# coroutines
d
So I want to traverse a read only (or frozen if you will) tree concurrently with coroutines.
Copy code
sealed class Tree {
    data class Parent(val children: List<Tree>): Tree()
    data class Leaf(val value: Int): Tree()
}

fun Tree.simpleSum(): Int {
    return when (this) {
        is Tree.Parent -> children.map { it.simpleSum() }.sum()
        is Tree.Leaf -> value
    }
}

fun Tree.concurrentSum(): Int {
    return when (this) {
        is Tree.Parent -> runBlocking {
            children.map { async { it.simpleSum() } }
                .awaitAll().sum()
        }
        is Tree.Leaf -> value
    }
}

suspend fun Tree.questionableSum(): Int {
    return when (this) {
        is Tree.Parent -> coroutineScope {
            children.map { async { it.questionableSum() } }
                .awaitAll().sum()
        }
        is Tree.Leaf -> value
    }
}
I basically want to sum up all the nodes in the tree. Right now I create a
Job
for every immediate child of the root (
concurrentSum
), but I might not be using all the parallelism available. I'm tempted to recursively create a
Job
at every node (
questionableSum
) which would use all the parallelism but I get the feeling that that's not the way to go. Is there a "right" way to go about this?
1
b
Parallel is explicit, which is exactly what you achieve with your
questionableSum
implementation. What is the feeling that you're getting? There are certainly alternatives, but not sure that it would necessarily be "better" or more "right"
1
d
The feeling is mostly from the overhead of creating a job for every node.
b
That's the beautiful part of jobs is they're relatively cheap for spinning off a bunch of concurrent jobs