Actors and Structured State Management
Use actor-style patterns to serialize state access in concurrent code.
What Is an Actor?
An actor is a coroutine that owns private mutable state and communicates via a channel. External code never accesses the state directly — only via messages.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
sealed class CounterMsg
object Increment : CounterMsg()
class GetCount(val response: CompletableDeferred<Int>) : CounterMsg()
fun CoroutineScope.counterActor() = actor<CounterMsg> {
var counter = 0
for (msg in channel) {
when (msg) {
is Increment -> counter++
is GetCount -> msg.response.complete(counter)
}
}
}Using the Actor
Send messages to the actor using send. The actor processes them one at a time, serializing state access.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
// (CounterMsg sealed class from previous scene)
fun main() = runBlocking {
val counter = counterActor()
repeat(100) { counter.send(Increment) }
val response = CompletableDeferred<Int>()
counter.send(GetCount(response))
println("Count: ${response.await()}") // 100
counter.close()
}All lessons in this course
- Channel Basics: send, receive, and close
- Channel Types: Rendezvous, Buffered, Conflated, Unlimited
- Mutex and Semaphore for Shared State
- Actors and Structured State Management