2024. 11. 27. 13:58ㆍKotlin
코틀린(Kotlin)에서 async
는 비동기적으로 작업을 수행하고 결과를 반환하는 코루틴 빌더입니다. async
는 launch
와 비슷하지만, launch
는 결과를 반환하지 않는 반면, async
는 Deferred
객체를 반환하여 나중에 결과를 얻을 수 있습니다. Deferred
는 Job
의 하위 클래스이며, 비동기 작업의 결과를 나타냅니다.
async의 기본 사용법
async
는 비동기적으로 작업을 수행하고, 결과를 기다리기 위해 await
함수를 사용합니다. 다음은 기본적인 사용 예제입니다:
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred: Deferred<Int> = async {
// Some long-running computation
delay(1000L)
42
}
// Do some other work here if needed
val result = deferred.await() // Wait for the result
println("Result: $result")
}
위 예제에서 async
블록은 백그라운드에서 실행되며, deferred
객체를 반환합니다. deferred.await()
를 호출하면 결과가 준비될 때까지 기다립니다.
async와 await를 사용한 병렬 처리
async
와 await
를 사용하면 여러 비동기 작업을 병렬로 실행할 수 있습니다. 다음은 두 개의 비동기 작업을 병렬로 실행하는 예제입니다:
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred1: Deferred<Int> = async {
delay(1000L)
10
}
val deferred2: Deferred<Int> = async {
delay(2000L)
20
}
// Wait for both results
val result1 = deferred1.await()
val result2 = deferred2.await()
println("Result 1: $result1")
println("Result 2: $result2")
}
위 예제에서 두 async
블록은 병렬로 실행되며, 각각 1초와 2초 동안 일시 중단됩니다. await
를 사용하여 두 결과를 모두 기다린 후 출력합니다.
async와 CoroutineScope
async
는 CoroutineScope
내에서 호출되어야 합니다. runBlocking
, launch
, async
등은 모두 CoroutineScope
를 생성합니다. 다음은 CoroutineScope
를 명시적으로 사용하는 예제입니다:
import kotlinx.coroutines.*
fun main() = runBlocking {
val scope = CoroutineScope(Dispatchers.Default)
val deferred = scope.async {
delay(1000L)
"Hello, World!"
}
val result = deferred.await()
println(result)
}
예외 처리
async
블록 내에서 발생한 예외는 await
를 호출할 때 전파됩니다. 따라서 await
를 호출할 때 예외 처리를 할 수 있습니다:
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred = async {
throw Exception("Something went wrong")
}
try {
deferred.await()
} catch (e: Exception) {
println("Caught exception: ${e.message}")
}
}
async와 구조적 동시성
코루틴은 구조적 동시성을 지원하며, 이는 부모 코루틴이 완료될 때 자식 코루틴도 함께 취소됨을 의미합니다. async
도 이 원칙을 따릅니다:
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
val deferred = async {
delay(1000L)
42
}
println("Result: ${deferred.await()}")
}
delay(500L)
job.cancel() // Cancels the parent job and its children
}
위 예제에서 job.cancel()
을 호출하면 launch
블록과 그 안의 async
블록이 모두 취소됩니다.
'Kotlin' 카테고리의 다른 글
Yield (0) | 2024.11.27 |
---|---|
Launch (0) | 2024.11.27 |
Dispatchers (0) | 2024.11.27 |
Continuation (0) | 2024.11.27 |
Coroutine - Suspend (1) | 2024.11.20 |