📌 Kotlin Coroutines의 CloseableCoroutineDispatcher
이해하기
1. 개요
CloseableCoroutineDispatcher
는 코루틴 디스패처 중 하나로, 새로운 작업을 거부하고 관련된 모든 리소스를 정리할 수 있는 close()
메서드를 제공합니다. 주로 java.lang.Executor
나 kotlin.native.Worker
를 기반으로 하는 디스패처에서 사용됩니다.
2. 주요 기능
- 작업 거부:
close()
메서드를 호출하면 새로운 작업의 디스패치가 거부됩니다. - 리소스 정리: 디스패처와 관련된 모든 리소스가 정리됩니다.
3. 사용 예시
newSingleThreadContext
함수를 사용하여 CloseableCoroutineDispatcher
를 생성하고 사용하는 예시입니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val dispatcher = newSingleThreadContext("MyThread")
val job = launch(dispatcher) {
println("Running in thread: ${Thread.currentThread().name}")
}
job.join()
dispatcher.close() // 디스패처 닫기
}
위 예시에서는 newSingleThreadContext
를 통해 단일 스레드 컨텍스트를 생성하고, 해당 디스패처에서 코루틴을 실행한 후, 작업이 완료되면 close()
메서드를 호출하여 디스패처를 닫습니다.
4. 주의사항
CloseableCoroutineDispatcher
는 실험적인 API로, 향후 변경될 수 있습니다. 사용 시 주의가 필요합니다.close()
메서드를 호출한 후에도 이전에 제출된 작업은 여전히 실행되지만, 새로운 작업은 거부됩니다.
📌 원본 출처
본 문서의 내용은 Kotlin 공식 문서를 참고하여 작성되었습니다. 자세한 내용은 아래 공식 문서를 통해 확인할 수 있습니다.
'Kotlin > kotlinx.coroutines' 카테고리의 다른 글
CompletableJob (0) | 2025.02.07 |
---|---|
CompletableDeferred (0) | 2025.02.07 |
CancellableContinuation (0) | 2025.02.07 |
cancelChildren (0) | 2025.02.07 |
cancelAndJoin (0) | 2025.02.07 |