I am quite familiar with parallel programming using threads, and I have enough experience to be able to write robust threaded code.
However, in my current project I would like to get more experience with Kotlin coroutines, and I think I have found a good place to experiment with them. Before committing on a design, I’d like input from people with more Kotlin coroutine experience than me as to what would be the best approach.
Simplified to its simplest form, the use case is as follows:
Assume a large array (millions of elements) and a function that perform an operation on a value and return the result.
fun getResult(index: Int): Value
When computing the result, the implementation of getResult
will recursively compute the result of some number of other indexes. In the most extreme case, reading the result of one index will implicitly compute the result of every single other value.
It is impossible to know beforehand which values will be retrieved, and in what order. However, in most cases all or almost all) values will be computed.
Obviously the best way to handle this is to create an array of all the results, populate it will nulls, and then simply fill in the results as they are computed, returning previous results if they are available.
Now that I’ve explained the scenario, the question is how I would parallelise this computation, specifically with coroutines in mind. I know how I would do it in pure Java will just threads low-level concurrency primitives, but I can’t really get that design to fit with how you are supposed to do things with coroutines in Kotlin.