- Discuss coroutines and channels in modern architecture.
- Concurrency vs Parallelism with real-world examples.
- Simple to advanced concurrency patterns in Kotlin.
28. Pipelinesfun CoroutineScope.produceNumbers() = produce<Int> {
var x = 1
while (true) send(x++) // infinite stream of integers starting from 1
}
fun CoroutineScope.square(numbers: ReceiveChannel<Int>): ReceiveChannel<Int> = produce {
for (x in numbers) send(x * x)
}
29. Pipelinesfun CoroutineScope.produceNumbers() = produce<Int> {
var x = 1
while (true) send(x++) // infinite stream of integers starting from 1
}
fun CoroutineScope.square(numbers: ReceiveChannel<Int>): ReceiveChannel<Int> = produce {
for (x in numbers) send(x * x)
}
fun pipeline() = runBlocking {
val numbers = produceNumbers() // produces integers from 1 and on
val squares = square(numbers) // squares integers
for (i in 1..5) println(squares.receive()) // print first five
println("Done!") // we are done
coroutineContext.cancelChildren() // cancel children coroutines
}
33. val repeats = 10_000
val p1 = producer("A", repeats)
val p2 = producer("B", repeats)
val p3 = producer("C", repeats)
val results = ConcurrentHashMap<String, Int>()
repeat(repeats) {
val result = select<String> {
p1.onReceive { it }
p2.onReceive { it }
p3.onReceive { it }
}
results.compute(result) { k, v ->
if (v == null) {
1
} else {
v + 1
}
}
}
println(results)
{A=8235, B=1620, C=145}
{A=7850, B=2062, C=88}
{A=7878, B=2002, C=120}
{A=8260, B=1648, C=92}
{A=7927, B=2011, C=62}
34. val repeats = 10_000
val p1 = producer("A", repeats)
val p2 = producer("B", repeats)
val p3 = producer("C", repeats)
val results = ConcurrentHashMap<String, Int>()
repeat(repeats) {
val result = selectUnbiased<String> {
p1.onReceive { it }
p2.onReceive { it }
p3.onReceive { it }
}
results.compute(result) { k, v ->
if (v == null) {
1
} else {
v + 1
}
}
}
println(results)
{A=3336, B=3327, C=3337}
{A=3330, B=3332, C=3338}
{A=3334, B=3333, C=3333}
{A=3334, B=3336, C=3330}
{A=3332, B=3335, C=3333}
35. Selecting on close
val p1 = produce {
repeat(10) {
send("A")
}
}
val p2 = produce {
repeat(5) {
send("B")
}
}
runBlocking {
repeat(15) {
val result = selectUnbiased<String> {
p1.onReceive {
it
}
p2.onReceive {
it
}
}
println(result)
}
}
36. Selecting on close
val p1 = produce {
repeat(10) {
send("A")
}
}
val p2 = produce {
repeat(5) {
send("B")
}
}
runBlocking {
repeat(15) {
val result = selectUnbiased<String> {
p1.onReceiveOrNull {
it
}
p2.onReceiveOrNull {
it
}
}
println(result)
}
}