1. Why cleanup in coroutines is part of the contract
Sunjohang jeogin code-reul sseul ttae, brain-eun aju dan순han geurim-eul joahamnida: “meonjeo A-reul 하고, geudaeum B, geudaeum C.” Coroutine-eun i geurim-eul kkaeji anseumnida (odeuryeo “jeongsangjeogin sunseo”cheoreom 느끼게 해juseumnida). Hajiman 현실-eun se beonjjae 변수를 deohamnida: code-ga deo ppalli kkeutnal su itda, geurigo geu kkeutnami 여러 bangbeop-euro ireonan-daneun geotipnida. Geureohgo coroutine-eseoneun i geosi teukbyeolhan geosi anira “basic reality”imnida: cancel(), exception, ireun return.
Structured concurrency-eseo-neun teukhi jungyohamnida: eoneu han bubun-ui operation-i meomchumyeon dareun bubundeuldo hamkke meomchul su itgo (ttoneun meomchwo야 하고), geurigo you-neun “trash”reul namgigo sipji anseumnida: set doeeo beorin flag isLoading, banman eobdeiteu doen state, “yeongwonhan spinner”, 닫히지 않은 resource deung. Structured concurrency-raneun concept-eun malhaet죠: coroutine-deul-eun hierarchically controllable-haeya 하고, 예측 가능하게 종료되어야 합니다.
Han coroutine-ui lifecycle-eul dan순han scheme-euro saenggakhaebopsida:
stateDiagram-v2
[*] --> Running
Running --> Completed: seonggongjeogeuro kkeutkkaji 도달
Running --> Cancelled: cancel()
Running --> Failed: exception
Completed --> [*]
Cancelled --> [*]
Failed --> [*]
Oneul lecture-ui focus: “modeun geoseul jeongrihaneun majimak step”ga eotteon exit-eseodo silhaengdoerok code-reul sseuneun beobeul baewobnida.
2. try/finally as a completion guarantee
finally in Kotlin: a quick reminder
Gakkeum-eun 1bun jeongdo “coroutine-eun eopda”고 chakhagohgo, try/finallyui basic idea-reul tteoollineun geosi yuyonghamnida. Kotlin-eseo finally block-eun eotteon gyeolgwa-eseodo silhaengdoeeoya haneun dongjag-eul sseuneun jariimnida: error-ga nateun geos-i든 아니든, tryeseo returneuro 나갔든, kkeutkkaji jinhaenghaet든.
Dareun jungyohan (geurigo jaju itgyeojineun) 사실: Kotlin-eseo tryneun must로 catchna finally (ttoneun dul da)reul gajyeoya 합니다. 즉, “그냥 try { ... }”reul sseul sun eopsseumnida — compiler-ga heoyonghaji 않습니다.
Coroutine eopsi, intuition-eul saeropge haegi wihan mini example:
fun main() {
try {
println("Start") // Start
error("boom")
} finally {
println("Cleanup") // Cleanup
}
// println("End") // error(...) ttaemun-e 여gi-kkaji oji motham
}
Geurigo style-e gwanhan jageun remark: Kotlin-eseo-neun } finally { reul han jul-e sseuneun geosi ilbanjeogimnida — formatting convention-ui ilbuigo, i hyeongtae-ga much easier to read-imnida.
Coroutine cancellation: why finally still runs
“Coroutine cancel”eul cheoeum deureumyeon, execution-eul jeongmal instant-ro jukineun “Kill -9” 버튼-eul tteoollig 쉬umnida. Hajiman ije-neun algo it죠: cancellation-eun stop requestigo, coroutine-eun gajang gakkeoun suspension point (delay(), wait, deung)eseo ttoneun jasin-i isActivereul chekhamyeon “dongui”hago meomchumnida.
Geureohgo oneul-ui key point: cancellation-do coroutine exitimnida. Exit라면, finallyga “mun-eul datgo bul-eul kkeuneun” bojangdoen chance-ga 됩니다.
Idea-reul gajang jeopge boyeojuneun jageun example-reul bopsida:
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
repeat(10) { i ->
delay(50)
println("working $i") // working 0, working 1, ...
}
} finally {
println("cleanup runs anyway") // cleanup runs anyway
}
}
delay(130)
job.cancelAndJoin()
println("main finished") // main finished
}
Yeogi-eseo jungyohan geot-eul 합니다: dan순히 cancel()i 아니라 cancelAndJoin(). 즉 “meomchwo달라-go malhaego coffee-reul masireo ganeun” geosi 아니라, yocheonghago, jeongmal kkeutnasseuneunji gidarimnida. Geuryeomyeon coroutine-ga silje-ro 종료되osseugo, geu gwajeong-eseo finallyreul silhaenghal sigan-do hwaksilhi gajimnida.
3. Where to keep cleanup: inside the coroutine and by responsibility levels
“Control from outside, clean up inside”: cancelAndJoin() + try/finally
Coroutine-eul cheoeum sseujagi sijakhaneun saramdeul-eun cleanup-eul “bakkat”eseo 하려go 하는 gyeong-u-ga jaju itsseumnida: “cancel-doemyeon — geureom eoneu jijeom-eseo든 cancel() dwie flag-reul set하고, message-reul 출력하고...” Ige gakkeum-eun works 합니다, scenario-ga aju jageul ttae-neun. Hajiman coroutine-ga jogeumman 복잡해져도, exit point-ga 여러 개가 되면, i 접근은 “eodiseo kkeutnasseulkkayo?” game-i 되어버립니다.
Jeong상jeogin discipline-eun ireoh습니다: bakkateseoneun lifecycle-eul control하고 (cancelAndJoin(), join()), 안eseoneun coroutine-ga try/finallyro cleanup-eul bojang합니다. Coroutine “naebu”ga gajang jal bo이는 건, geu coroutine-ga mwol “own”haneunjipnida: eotteon flags, eotteon temporary resources, eotteon logic.
Uri-ui 가상 console project-reul 계속해봅시다 (예: “BudgetBuddy”: 지출 기록과 보고서 생성). App state-ga 있고, eoneu command-ga “긴 보고서 export”reul 실행합니다. Export-neun cancel 가능하다고 해봅시다 (사용자가 마음을 바꿀 수 있으니까요).
Gajang dan순han state-reul mandeul-eobopsida:
data class AppState(
var exportInProgress: Boolean = false
)
Ije export-reul 시작하는 function-eun Jobeul return합니다. Note: Jobeun “export result”ga 아니라, 정확히 “lifecycle control handle”imnida. Geuraeseo cleanup-eul i Job naebu-e du는 게 jayeonseureop습니다.
import kotlinx.coroutines.*
fun startReportExport(scope: CoroutineScope, state: AppState): Job =
scope.launch {
state.exportInProgress = true
try {
repeat(5) { step ->
delay(80)
println("export step ${step + 1}/5") // export step 1/5 ...
}
println("export done") // export done
} finally {
state.exportInProgress = false
println("export cleanup: flag reset") // export cleanup: flag reset
}
}
Ije bakkat(예: main())eseo-neun export-reul cancelhaedo, hangsang 확신할 수 있습니다: flag-neun eonjena 정상으로 돌아옵니다.
Cleanup in child coroutines: finally at each level
Parent coroutine-eseo han beon “keun” try/finallyreul sseugo “igeuro chungbun”이라고 생각하기 쉽습니다. Hajiman structured concurrency-neun joeun 습관을 garyeochimnida: 각 level은 자신이 소유한 것(owned resources)을 스스로 정리해야 합니다.
Parent-neun “operation jeonche”reul own하고, child-neun local things를 own할 수 있습니다: temporary buffer, 자신의 status, 자신의 계산 일부. Geuraeseo finallyga parent에도, children에도 있는 게 자연스럽고 (많이 올바른) 경우가 많습니다: 서로 다른 것을 정리하기 때문입니다.
Example: parent-ga export worker du gaereul launch합니다 — hananeun data prepare, dareun hananeun data-reul “packaging” (실제로는 무엇이든 될 수 있지만, 여기서는 delay()ro 흉내만 냅니다).
import kotlinx.coroutines.*
fun main() = runBlocking {
val parent = launch {
try {
launch {
try {
delay(60)
println("prepare done") // prepare done
} finally {
println("prepare cleanup") // prepare cleanup
}
}
launch {
try {
delay(90)
println("pack done") // pack done
} finally {
println("pack cleanup") // pack cleanup
}
}
} finally {
println("parent cleanup") // parent cleanup
}
}
parent.join()
}
Yeogi-eseo point-neun “line order”ga 아닙니다 (순서는 바뀔 수 있습니다). Point-neun cleanup-ga responsibility byeollo 나뉘어 있다는 것입니다. Parent-neun parent-ui 것을, children-eun children-ui 것을 보장합니다.
4. Cleanup on errors, and what finally should contain
Cleanup on errors: try/finally doesn’t “fix”, but it cleans
Miseuhan 심리적 함정이 있습니다: finallyga “항상 실행”되니까, error를 무서워하지 않아도 된다고 느끼는 것. Geureon-de 아닙니다. 무서워할 수도(때로는 반드시) 있습니다. 다만 이제 error가 “mess”를 남기지 않게 됩니다.
Role-eul 명확히 합시다: finallyneun exception-eul catch하지 않습니다. Exit 시점에 보장적으로 실행될 뿐이고, 그 다음 exception은 catch에서 처리되거나, scope boundary 위로 “propagate”됩니다.
Export example로 보여보겠습니다: 3번째 step에서 갑자기 error가 나도, cleanup은 여전히 실행됩니다:
import kotlinx.coroutines.*
fun main() = runBlocking {
val state = AppState()
val job = launch {
state.exportInProgress = true
try {
repeat(5) { step ->
delay(50)
if (step == 2) error("disk is full (pretend)")
println("step ${step + 1}") // step 1, step 2
}
} finally {
state.exportInProgress = false
println("cleanup after error") // cleanup after error
}
}
try {
job.join()
} catch (e: Exception) {
println("caught in main: ${e.message}") // caught in main: disk is full (pretend)
}
println("flag = ${state.exportInProgress}") // flag = false
}
I example-ui 요지는 “어디에서 exception을 catch할지”가 아닙니다(그것은 이전 lecture에서 다뤘습니다). 요지는 보장입니다: crash가 나더라도 state는 올바른 상태로 되돌아옵니다.
What to put in finally — and what not to
finallyneun 아주 강력한 도구이고, 그래서 남용하기 쉽습니다. 몇 번 성공 사례를 보고 나면: “오, 그럼 finally에서 못한 거 다 하면 되겠다”라는 유혹이 생깁니다. 그리고 그렇게 finally-block 80줄짜리가 생기고, 그 block 자체가 crash할 수 있고, hang될 수 있고, 코드를 “드라마”로 만들어버립니다.
Uri ipeleul wihan practical rule: cleanup-eun 짧고, 빠르고, 최대한 신뢰 가능해야 합니다. Flag를 정상으로 되돌리고, 명확한 종료 로그를 남기고, 반드시 닫아야 하는 것을 닫고, 복잡한 branching을 하지 않는 게 좋습니다.
Jageun table-eul 머릿속에 두면 편합니다:
| finallyeseo haegi joeun geot | Why it’s good | finallyeseo haegi wiheomhan geot | Why it’s risky |
|---|---|---|---|
| State flag reset (exportInProgress = false) | Fast and predictable | Large business logic | It can crash and “overwrite” the original root cause |
| Print a final message/log | Helps debugging | Many actions that can also throw exceptions | Debugging turns into detective work |
| Release a locally created resource | Return the system to a normal state | Assume “if cancelled, cleanup isn’t needed” | It’s needed precisely because it was cancelled |
Tto han 번, finallyui basic meaning-eul gieokhaeya 합니다: Kotlin-eseo-neun tryui 어떤 결과에서도 실행되어야 하는 code를 위한 것입니다.
Geurigo yes, Kotlin-eseo try/finallyreul compact하고 읽기 좋게 쓰는 게 일반적입니다 — 이는 눈으로 검토하기 쉬워져 실수 확률을 줄여줍니다.
5. Mini scenario: export, cancellation, and guaranteed cleanup
Ije jageun “end-to-end” scenario-reul mandeul-eobopsida: export-reul start하고, jom dongan 돌아가게 둔 다음, “사용자가 취소했다”reul 흉내 내고, cleanup이 항상 실행되는지 확인합니다. 실제 CLI라면 command input이겠지만, oneul-eun command parsing을 가져오지 않기 위해 timer로 cancel하겠습니다.
import kotlinx.coroutines.*
data class AppState(var exportInProgress: Boolean = false)
fun startReportExport(scope: CoroutineScope, state: AppState): Job =
scope.launch {
state.exportInProgress = true
try {
repeat(10) { i ->
delay(40)
println("export tick $i") // export tick 0, 1, 2...
}
println("export finished normally") // (won’t reach this on cancel)
} finally {
state.exportInProgress = false
println("export cleanup (always)") // export cleanup (always)
}
}
fun main() = runBlocking {
val state = AppState()
val exportJob = startReportExport(this, state)
delay(130)
println("cancel requested") // cancel requested
exportJob.cancelAndJoin()
println("flag = ${state.exportInProgress}") // flag = false
}
flagga hangsang falsero 나오는 것을 본다면, dangsin-eun 가장 교활한 bug class 중 하나를 이긴 것입니다: “working indicator가 영원히 켜져 있음”과 “cancel 후 state가 정상으로 돌아오지 않음”.
6. Typical cleanup mistakes in coroutines
Mistake #1: doing cleanup “outside” and forgetting other exit paths.
Bakkat code-eseo join() dwie만 flag를 reset하거나 “done”을 출력하면, coroutine-ga exception으로 종료되었거나, cancel되었거나, return 때문에 일찍 빠져나간 경우를 놓치게 됩니다. Geuraeseo app state-ga 현실과 어긋납니다: 이미 끝났는데도 UI/logic은 아직 진행 중이라고 생각하게 됩니다.
Mistake #2: calling cancel() but not waiting for completion, while assuming cleanup already ran.
Cancellation은 요청이지 즉시 전원 차단이 아닙니다. Cleanup이 반드시 실행되었어야 한다면(대부분 그렇습니다), join()으로 기다리거나, 처음부터 cancelAndJoin()을 사용해야 합니다. 그렇지 않으면 coroutine의 “정리”는 조금 뒤에 일어나고, 여러분의 코드는 이미 다음으로 달려가 버립니다.
Mistake #3: turning finally into a “second main program”.
finally가 커지면, 새로운 error의 source가 됩니다. 가장 나쁜 상황은 cleanup이 exception으로 실패해서, 원래의 원인(디버깅해야 했던 이유)을 잃어버리는 것입니다. finally는 지루하고, 짧고, 신뢰 가능해야 합니다 — 그게 superpower입니다.
Mistake #4: not separating responsibility between parent and children.
Parent coroutine이 “전체 작업”만 소유하고, child coroutines가 자신만의 temporary resource나 state를 만든다면, 모든 것을 한 곳에서 정리하려는 시도는 불편하고 실수하기 쉽습니다. 각 level마다 작은 try/finally를 두고, 자신이 만든 것만 정리하게 하는 편이 훨씬 안정적입니다.
Mistake #5: confusing “cancellation isn’t an error” with “cleanup isn’t needed on cancellation”.
맞습니다, cancellation은 정상 시나리오일 수 있고 꼭 문제가 아닙니다. 하지만 cancellation이 정상적이기 때문에, cleanup도 정상적이고 필수적이어야 합니다: flag reset, operation 종료 처리, state를 consistent하게 만들기. 그렇지 않으면 cancellation이 “반쯤 망가진 앱”을 만들고, 이후에 이상한 동작을 하게 됩니다.
GO TO FULL VERSION