Kotlin/포스팅

코루틴 구조적 동시성

짜집퍼박사(짜박) 2024. 1. 7. 14:18

코루틴의 구조적 동시성(Structured Concurrency)은 비동기 코드를 더욱 안전하고 예측 가능하게 만들어주는 개념입니다. 이는 코루틴의 생명주기와 범위를 명확하게 정의하여 코루틴이 실행되는 동안의 상태와 예외 처리를 효과적으로 관리합니다.

 

1. Job과 CoroutineScope

코루틴은 Job과 CoroutineScope로 구성됩니다. Job은 특정 코루틴의 생명주기와 상태를 나타내며, CoroutineScope는 여러 코루틴을 묶는 역할을 합니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = Job() // 코루틴의 생명주기를 관리하는 Job 생성

    val coroutineScope = CoroutineScope(Dispatchers.Default + job) // 코루틴 범위 생성

    coroutineScope.launch {
        // 비동기 작업
        delay(1000)
        println("Coroutine is running.")
    }

    println("Main thread is not blocked.")
    delay(2000)

    job.cancel() // 코루틴을 취소하고 해당 Job을 종료
    println("End")
}

 

2. Structured Concurrency의 예외 처리

구조적 동시성은 예외 처리를 효과적으로 다루는 데 중점을 둡니다. 부모 코루틴이 실패하면 해당 부모의 자식 코루틴도 모두 취소되어 안전한 종료가 가능합니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    try {
        coroutineScope {
            launch {
                // 자식 코루틴
                delay(500)
                throw Exception("Exception in child coroutine")
            }

            launch {
                // 다른 자식 코루틴
                delay(1000)
                println("Another child coroutine is running.")
            }
        }
    } catch (e: Exception) {
        println("Caught an exception: ${e.message}")
    }

    println("End")
}

 

3. cancel과 join

코루틴이 취소되면 해당 코루틴의 Job에 의해 모든 하위 코루틴도 취소됩니다. join 함수를 사용하여 특정 코루틴이 완료될 때까지 기다릴 수 있습니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        launch {
            delay(500)
            println("Child coroutine 1 is done.")
        }

        launch {
            delay(1000)
            println("Child coroutine 2 is done.")
        }
    }

    delay(700)
    job.cancel() // 부모 코루틴 취소
    job.join() // 부모 코루틴이 완료될 때까지 대기

    println("End")
}

 

4. SupervisorJob

SupervisorJob은 부모 코루틴이 실패하더라도 자식 코루틴에는 영향을 미치지 않도록 하는 역할을 합니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val supervisorJob = SupervisorJob()

    with(CoroutineScope(Dispatchers.Default + supervisorJob)) {
        launch {
            println("Start parent coroutine")
            delay(1000)
            println("End parent coroutine")
        }

        launch {
            println("Start child coroutine")
            delay(500)
            throw Exception("Exception in child coroutine")
        }

        delay(2000)
    }

    println("End")
}

구조적 동시성은 코루틴을 사용할 때 예측 가능한 동작을 제공하며, 코루틴 간의 생명주기와 예외 처리를 효과적으로 관리할 수 있게 합니다. 이를 통해 안전하고 유지보수가 용이한 비동기 코드를 작성할 수 있습니다.

 

With ChatGPT

'Kotlin > 포스팅' 카테고리의 다른 글

코루틴 흐름 제어  (0) 2024.01.09
코루틴 문맥  (0) 2024.01.07
코루틴 영역  (0) 2024.01.07
코루틴 빌더  (0) 2024.01.07
코루틴과 일시 중단 함수  (0) 2024.01.07