PHpullh
학습 라이브러리/Kotlin/액터 모델 (Actor Model)

KOTLIN · 비동기

액터 모델 (Actor Model)

액터는 메시지 기반으로 상태를 캡슐화하는 동시성 패턴입니다. 채널을 통해 직렬화된 접근을 보장합니다.

비동기고급actormessage-passingconcurrencychannel

핵심 설명

액터는 메시지 기반으로 상태를 캡슐화하는 동시성 패턴입니다. 채널을 통해 직렬화된 접근을 보장합니다.

Kotlin code

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*

sealed class CounterMsg {
    data object Increment : CounterMsg()
    data class Get(val response: CompletableDeferred<Int>) : CounterMsg()
}

fun CoroutineScope.counterActor() = actor<CounterMsg> {
    var count = 0
    for (msg in channel) {
        when (msg) {
            is CounterMsg.Increment -> count++
            is CounterMsg.Get -> msg.response.complete(count)
        }
    }
}

fun main() = runBlocking {
    val counter = counterActor()

    // 동시에 증가
    val jobs = List(100) {
        launch {
            repeat(1000) {
                counter.send(CounterMsg.Increment)
            }
        }
    }
    jobs.forEach { it.join() }

    // 결과 조회
    val response = CompletableDeferred<Int>()
    counter.send(CounterMsg.Get(response))
    println("카운터: ${response.await()}")  // 100000
    counter.close()
}

학습 팁

액터 패턴은 뮤텍스 없이도 스레드 안전합니다. 모든 상태 변경이 채널을 통해 직렬화되기 때문입니다.

주의할 점

actor 빌더는 실험적 API입니다. 프로덕션에서는 Mutex를 사용하는 것이 더 안정적일 수 있습니다.

자주 묻는 질문

액터 모델 (Actor Model)란 무엇인가요?

액터는 메시지 기반으로 상태를 캡슐화하는 동시성 패턴입니다. 채널을 통해 직렬화된 접근을 보장합니다.

액터 모델 (Actor Model) 학습 시 주의할 점은 무엇인가요?

actor 빌더는 실험적 API입니다. 프로덕션에서는 Mutex 를 사용하는 것이 더 안정적일 수 있습니다.