Summary - Concurrency patterns
- Kotlin course
- Advanced
- Lesson 72/83
- 5 min
Combine Mutex, Channel and rate limiter to write a work queue.
Summary - Concurrency patterns
In this group you saw concurrency patterns: mutual exclusion with Mutex, limiting with Semaphore, producer-consumer with Channel, request limits with rate limiter and fault isolation with circuit breaker.
This lesson includes a small task that combines three of them: you will produce values into a Channel and sum them with a for loop. This pattern brings together the foundation of concurrency patterns.
Practice Summary: sum values with Channel
Open main with runBlocking. Create val ch = Channel<Int>(3); send 10, 20, 30; call close(). Initialize var sum = 0 and sum with for (v in ch) sum += v, then print println(sum).
Starter code
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.runBlocking
// open main with runBlocking
// create a three-buffer channel, send three values, close, sum with for and printSample solution
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val ch = Channel<Int>(3)
ch.send(10)
ch.send(20)
ch.send(30)
ch.close()
var sum = 0
for (v in ch) sum += v
println(sum)
}Expected output
60
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool ensures only one coroutine enters a code block?
- Channel
- Semaphore
- Mutex Correct answer
- RateLimiter
Explanation: Mutex provides single coroutine access.
2 Match the concurrency tools
| Term | Meaning |
|---|---|
Mutex |
Mutual exclusion |
Semaphore |
Bounded parallelism |
Channel |
Producer-consumer |
CircuitBreaker |
Fault isolation |
3 Complete the withLock call
val m = Mutex()
m.____ { println("ok") }
val m = Mutex()
m.withLock { println("ok") }
Explanation: withLock acquires and releases the lock.