개발일지

Kotlin in A..Z - Coroutine(1) 개념 본문

Kotlin (코틀린)

Kotlin in A..Z - Coroutine(1) 개념

강태종 2020. 10. 8. 23:54

Gradle 설정

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7")
}

Thread vs Coroutine

Thread와 Coroutine은 동시성을 보장하기 위한 기술이다.

 

Thread

Preempting Scheduling
자원을 서로 차지하려고 노력하고 OS가 Context Switching을 통해 Thread에게 자원을 할당한다 -> Overhead발생

Thread자체 Stack메모리를 가지고 JVM Stack을 차지한다.

 

Coroutine

Cooperatively
처리 단위가 Thread가 아닌 Coroutine에서 제공하는 Job Object단위로 하나에 Thread에서 진행된다. Thread내에서 프로그래머가 직접 Switching을 한다. -> 하나의 Thread에서 Switching이 일어나기 때문에 Overhead를 최소한다.

Coroutine Job Object는 Heap메모리를 가지고 JVM Heap을 차지한다.

 


Coroutine

Coroutine을 시작하는 기본적인 방법이다.

import kotlinx.coroutines.*

fun main() {
    Thread(Runnable {
        for (i in 1..3) {
            println("I'm Thread $i")
            Thread.sleep(1000L)
        }
    }).start()

    GlobalScope.launch(Dispatchers.Default) {
        repeat(3) {
            println("I'm Coroutine $it")
            delay(1000L)
        }
    }
}
I'm Thread 1
I'm Coroutine 0
I'm Thread 2
I'm Coroutine 1
I'm Thread 3
I'm Coroutine 2

CoroutineContext

CoroutineContext는 코루틴을 어떻게 처리할지에 대한 정보입니다.


Dispatcher

Dispatcher는 CoroutineContext를 상속받아 어떤 쓰레드를 이용해서 동작할 것인지 정의해둔 것 입니다.

 

None : 실행된 코루틴 스코프에게 상속받는다.

 

Unconfined : 호출 쓰레드에서 실행하지만 멈췄다가 재개할 경우 재개한 쓰레드에서 실행한다.

-> 특정 쓰레드에 국한되지 않는 경우 적합

Main : 메인 쓰레드에서 실행한다.

-> 안드로이드에서 UI를 바꿀 때 적합, Job이 무거우면 부적합

 

IO : 네트워크, 디스크 사용 할때 사용합니다. 파일 읽고, 쓰고, 소켓을 읽고, 쓰고 작업을 멈추는것에 최적화되어 있습니다.

 

Default : Thread Pool에 할당한다. (GlobalScope.launch { }도 마찬가지)

 

runBlocking {
            launch {
                println("launch : ${Thread.currentThread().name}")
            }

            launch(Dispatchers.Unconfined) {
                println("launch(Dispatchers.Unconfined) : ${Thread.currentThread().name}")
            }

            launch(Dispatchers.Main) {
                println("launch(Dispatchers.Main) : ${Thread.currentThread().name}")
            }

            launch(Dispatchers.IO) {
                println("launch(Dispatchers.IO) : ${Thread.currentThread().name}")
            }

            launch(Dispatchers.Default) {
                println("launch(Dispatchers.Default) : ${Thread.currentThread().name}")
            }
        }
10-09 03:25:21.174 14754-14754/com.example.coroutine I/System.out: launch(Dispatchers.Unconfined) : main
10-09 03:25:21.184 14754-14754/com.example.coroutine I/System.out: launch : main
10-09 03:25:21.191 14754-14782/com.example.coroutine I/System.out: launch(Dispatchers.IO) : DefaultDispatcher-worker-3
10-09 03:25:21.191 14754-14781/com.example.coroutine I/System.out: launch(Dispatchers.Default) : DefaultDispatcher-worker-2

 

'Kotlin (코틀린)' 카테고리의 다른 글

Kotlin in A..Z - Coroutine(3) Cancel  (0) 2020.10.15
Kotlin in A..Z - Coroutine(2) 기본  (0) 2020.10.15
Kotlin in A..Z - 범위 지정 함수  (0) 2020.07.27
Kotlin in A..Z - Array  (0) 2020.07.21
Kotlin in A..Z (27) - reified  (0) 2020.07.19
Comments