협력적 취소: isActive와 ensureActive
isActive를 확인하고 ensureActive를 호출해 코루틴을 취소 가능하게 만들어 보세요.
협력적 취소: isActive와 ensureActive은(는) CoddyKit의 무료 Kotlin Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Kotlin Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Kotlin Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
협력적 취소가 필요한 이유
Kotlin 코루틴은 협력적 취소를 사용합니다. 취소된 코루틴은 취소 상태를 확인하는 방식으로 협력할 때만 중지됩니다. 촘촘한 CPU 반복문은 상태를 확인하기 전까지 중지되지 않습니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
var i = 0
while (true) { i++ } // never checks — never cancels!
}
delay(100)
job.cancel()
println("cancel sent but loop kept running until process ended")
}isActive 확인
isActive는 CoroutineScope의 프로퍼티이며 취소가 요청되면 false를 반환합니다. 반복문에서 이를 확인하면 코루틴이 취소에 협력하게 됩니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
var i = 0
while (isActive) {
i++
}
println("Loop exited after $i iterations")
}
delay(10)
job.cancel()
job.join()
}ensureActive()
ensureActive()는 코루틴이 취소되었을 때 CancellationException을 발생시킵니다. if (!isActive) throw CancellationException()을 바로 대체해 사용할 수 있습니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
repeat(1_000_000) {
ensureActive() // throws if cancelled
// heavy computation here
}
} catch (e: CancellationException) {
println("Cancelled at iteration")
throw e
}
}
delay(5)
job.cancel()
job.join()
}협력 지점으로서의 yield()
yield()는 코루틴을 잠시 중단하여 스케줄러가 취소 여부를 확인하고 다른 코루틴을 실행할 수 있게 합니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
repeat(10) { i ->
yield() // cooperative cancellation point + gives up scheduler
println("Step $i")
}
}
delay(2)
job.cancel()
job.join()
println("Done")
}isActive와 ensureActive 비교
조건부 로직에는 isActive를 사용합니다(예: 반복문을 정상적으로 빠져나오기). 취소를 즉시 예외로 전파하려면 ensureActive()를 사용합니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
repeat(100) { i ->
if (!isActive) {
println("Stopping at $i, cleaning up...")
return@launch
}
// work
}
}.also { delay(5); it.cancel(); it.join() }
}CancellationException은 특별합니다
CancellationException은 부모로 전파되지 않으며 정상적인 취소를 나타냅니다. 이를 절대 무시하지 말고 항상 다시 던지거나 전파되도록 두셔야 합니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
delay(1000)
} catch (e: CancellationException) {
println("Caught cancellation, rethrowing")
throw e // important!
}
}
delay(50)
job.cancel()
job.join()
println("Job state: ${job.isCancelled}")
}CPU 집약적 작업에서의 취소
CPU 집약적 작업에서는 자연스러운 확인 지점에 ensureActive() 또는 yield()를 삽입하여 적시에 취소할 수 있도록 하셔야 합니다.
import kotlinx.coroutines.*
suspend fun heavyCompute(n: Int): Long {
var result = 0L
for (i in 0..n) {
ensureActive()
result += i
}
return result
}
fun main() = runBlocking {
val job = launch(Dispatchers.Default) {
println(heavyCompute(1_000_000))
}
delay(10)
job.cancel()
job.join()
}isActive를 사용하는 사용자 지정 일시 중단 함수
모든 일시 중단 함수에서 coroutineContext.isActive를 사용하거나 currentCoroutineContext().isActive를 사용하여 isActive에 액세스할 수 있습니다.
import kotlinx.coroutines.*
suspend fun checkable() {
while (currentCoroutineContext().isActive) {
delay(10)
println("tick")
}
}
fun main() = runBlocking {
val job = launch { checkable() }
delay(35)
job.cancel()
job.join()
}리소스 정리와 취소
협력적 취소를 사용하더라도 finally 블록에서 리소스를 정리할 수 있으며, 취소 예외는 해당 블록을 통과해 계속 전파됩니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
repeat(100) { i ->
ensureActive()
delay(20)
println("Working $i")
}
} finally {
println("Cleanup done")
}
}
delay(50)
job.cancel()
job.join()
}isActive를 사용한 반복 조회
반복 조회 루프에는 isActive가 아주 잘 맞습니다. 코루틴이 취소될 때까지 반복 조회를 유지하면 됩니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
while (isActive) {
println("Polling...")
delay(100)
}
println("Poller stopped")
}
delay(350)
job.cancel()
job.join()
}Thread.interrupted()와의 차이
Java 스레드와 달리 Kotlin 코루틴은 인터럽트 플래그에 의존하지 않습니다. 취소를 예외와 범위 상태로 모델링하므로 합성 가능하고 구조화된 방식으로 동작합니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
// Kotlin way: cooperative via isActive / ensureActive
launch {
ensureActive()
println("Kotlin coroutine: cancellation is explicit and structured")
}
}빠른 확인
코루틴이 취소될 때 즉시 예외를 던지는 함수는 무엇인가요?
복습
협력적 취소에는 명시적인 확인 지점이 필요합니다. isActive는 조건부 종료에, ensureActive()는 즉시 예외를 던지는 데, 실행 양보는 일시 중단하고 스레드를 양보하는 데 사용합니다. CancellationException을 절대 무시하지 마십시오.
AI 튜터와 함께 Kotlin을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 51
- 레슨
- 203
자주 묻는 질문
“협력적 취소: isActive와 ensureActive” 강의는 무료인가요?
네 — “협력적 취소: isActive와 ensureActive” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Kotlin Academy 강의 전체를 잠금 해제할 수 있습니다. Kotlin Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“협력적 취소: isActive와 ensureActive”에서 뭘 배우나요?
isActive를 확인하고 ensureActive를 호출해 코루틴을 취소 가능하게 만들어 보세요. 브라우저에서 직접 실행하는 실습 코드로 Kotlin Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Kotlin Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Kotlin Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“협력적 취소: isActive와 ensureActive” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Kotlin Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Kotlin Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 협력적 취소: isActive와 ensureActive
- withTimeout과 withTimeoutOrNull
- finally와 NonCancellable로 정리하기
- 코루틴 계층 구조에서 취소 전파