I found the following article and wondered what th...
# coroutines
e
I found the following article and wondered what the Kotlin version might look like: https://dzone.com/articles/print-even-and-odd-numbers-using-two-threads-compl My solution: https://gist.github.com/edreyer/e3ac7fbdd6146806b3839d79262f63bd I’m still rather new to Kotlin, so not sure if this is the best. Would love comment on the gist if there is a better way
The kotlin version produces identical output and requires a lot less code to express. The cognitive load on reading this code feels substantially lower as well. Kotlin ❤️
s
Your Kotlin version may not print them in order... It's possible to see a bunch of "first" prints in a row or a bunch of "second" prints in a row. To print then in sequence, mimicking the
.join()
in the Java code, guaranteed a "first" then a "second", change the calls to
launch
to calls to
withContext
.
🙏 1
s
Instead of withContext, async/await would get the results twice as fast because withContext will wait for the result to return. See this code with some delays added to simulate long running code.
Copy code
public fun main() {
    withContextSolution()
    asyncSolution()
}

public fun withContextSolution(): Unit = runBlocking {
    println("\n***** withContext *****")
    val startTime = System.currentTimeMillis()

    val ctx1 = newSingleThreadContext("first")
    val ctx2 = newSingleThreadContext("second")

    (1..10).forEach {
        withContext(ctx1) {
            delay(1000)
            if (it % 2 == 1) println("$it ${Thread.currentThread().name}")
        }
        withContext(ctx2) {
            delay(1000)
            if (it % 2 == 0) println("$it ${Thread.currentThread().name}")
        }
    }

    println("Elapsed Time: ${System.currentTimeMillis() - startTime}")
}

public fun asyncSolution(): Unit = runBlocking {
    println("\n***** async / await *****")
    val startTime = System.currentTimeMillis()

    val ctx1 = newSingleThreadContext("first")
    val ctx2 = newSingleThreadContext("second")

    (1..10).forEach {
        val first = async(ctx1) {
            delay(1000)
            if (it % 2 == 1) println("$it ${Thread.currentThread().name}")
        }
        val second = async(ctx2) {
            delay(1000)
            if (it % 2 == 0) println("$it ${Thread.currentThread().name}")
        }
        first.await()
        second.await()
    }

    println("Elapsed Time: ${System.currentTimeMillis() - startTime}")
}
💯 1