본문 바로가기

Kotlin

kotlin Coroutine 쉽게 이해하기 2 - Context와 Dispatchers

코루틴 Context와 Dispatchers

  • CoroutineContext(kotlin 표준 라이브버리에 정의됨) 타입의 값으로 정의된 어떤 context에서 실행
  • 코루틴 context는 Job,Dispatcher 등 요소들의 집합

Dispatchers

해당 코루틴의 실행에 사용하는 스레드 결정한다.

코루틴의 실행을

  • 특정 쓰레드로 제한
  • 쓰레드 풀로 보냄
  • 제한을 받지 않는 상태

로 실행할 수 있다.

 

Dispatchers.Default

The default CoroutineDispatcher that is used by all standard builders like launch, async, etc if no dispatcher nor any other ContinuationInterceptor is specified in their context. It is backed by a shared pool of threads on JVM.
  • launch, async에서 사용하는 dispatcher
  • 백그라운드 스레드 풀에서 공유하여 사용

newSingleThreadContext

  • 코루틴을 실행할 새로운 스레드 생성
  • 비싼 자원이기 때문에 최상위 변수에 저장한 후 애플리케이션 전체에 걸쳐 사용해야 함
  • 혹은 더이상 필요하지 않은 경우 close() 함수 사용

Dispatchers.Unconfined

A coroutine dispatcher that is not confined to any specific thread. It executes initial continuation of the coroutine in the current call-frame and lets the coroutine resume in whatever thread that is used by the corresponding suspending function, without mandating any specific threading policy. Nested coroutines launched in this dispatcher form an event-loop to avoid stack overflows.

  • 해당 dispatcher는 호출한 스레드에서 코루틴을 시작하지만 첫 번째 suspension 지점까지만 시작
  • suspension이 끝나면 호출된 suspension 함수에 의해 다른 스레드로 코루틴을 재개함
  • CPU 시간 소모하지 않고 특정 스레드에 제한된 공유 데이터를 업데이트 하지 않는 코루틴에는 적합

  • unconfined 쓰레드 - delay 함수가 사용 중인 기본 executor 스레드에서 다시 실행됨
  • runBlocking에서 context를 상속받은 코루틴은 main 스레드에서 계속 실행됨

디버깅을 위한 코루틴 Naming

  • 특정 요청 처리나 특정 백그라운드 작업을 수행하는 중에는 이름을 정해주는게 좋음

context 요소 결합

명시적으로 지정된 dispatcher, coroutine을 동시에 실행할 수 있음