1. Coroutine cancellation model
JVMeseo file opeureisyeoneun botong blocking imnida: OSga 제어를 돌려줄 ttaekkaji threadga jinjja로 점유됩니다. Geuraeseo keun file boksa/cheoriui “Cancel button”eun 사치가 아니라 UXwa 안정성ui 기본 요소입니다: yongja-neun processreul jukiji 않고, datareul 망gachiji 않고, janggihan 작업을 예의 바르게 멈출 su isseoya 합니다.
Cancel은 “magia”ga 아니라 “agreement”입니다
Appeseo “Cancel” buttoni saenggimyeon 초보 programmer는 ireon kkumeul kkupnida: ije cancel()eul bulleo, 컴퓨터 deep aneseo jageun gnomi joseonhi modeun geoseul 멈chwo jul georaya. Hyeonsil-eun deo pyeongbeomhago, 솔직히 말해 더 유익합니다: Kotlin coroutine cancellationeun cooperativeimnida. Jeugeun, codega 스스로 “취소되었다”neun geoseul 인지하고, 정상적으로 종료haeya 한다는 뜻입니다.
Cooperative이라는 것은 단점이 아니라 예측 가능성의 보장입니다. Sanghwang-eul sangsanghaeboseyo: coroutineeul eotteon microsecondedo eotteon jomeseodo 멈chul su itdamyeon, geugeun 두 gaeui 논리적으로 연결된 동작 “사이”eseo 멈chul su 있고, datareul 반쯤만 처리된 상태로 남gyeo, 나중e “gakkeum filei 깨jineunde hw요일man” 같은 레벨ui bugreul 잡게 될 것입니다.
Coroutineeseoneun 더 단순합니다: cancel은 signal이고, dangsini hal 일은 긴 작업 중에 geu signal을 주기적으로 확인하고 “saram답게” 나가는 것입니다.
Wae file opeureisyeon-eun cancel()eul 자주 “deutji” mothal까요
Fileeun “variable memory”ga 아니라 OSwa disk와의 상호작용입니다. File, InputStream, OutputStream sujun-ui manheun opeureisyeon-eun blocking입니다: OSga 제어를 돌려줄 ttaekkaji threadga jinjja로 점유됩니다. Geurigo yeogi 중요한 미묘한 점이 있습니다: coroutineun blocking call jung-gan-e “kkyeo-deureoga” 즉시 취소할 su eopseumnida.
Botong scenario-neun ireon sikhimnida: Jobeul 취소haessjiman, 내부에서는 지금 당jang input.read(...) ga 수행 중입니다. Coroutineun read()ga 제어를 돌려준 daeum에야 취소에 반응할 su 있습니다(즉, byte 수 또는 -1eul return하거나, exceptioneul 던질 ttae).
Geuraeseo file taskeseo cancellationeun geuib “gajang gakkaun 편한 지점에서 멈춘다”neun wonchigeuro 처리되며, geu 편한 지점은 read/write loopui iteration 사이입니다.
Yeogiseo lecture-ui practical rule: keun file copy/cheori opeureisyeoneul cancel 가능하게 하려면, geugeul chunk loop(chunk 단위 읽기)로 작성하고, loop 안에서 주기적으로 “na-reul 취소haetneunji”reul 확인합니다.
2. Chunk loop — “handle and brake”
Chunk danwi로 file boksa
Meonjeo coroutine cancellation eopsi chunk loopreul 살펴봅sida — “올바른 복사” 기술로서요. Idea-neun gan단합니다: buffer(ye: 8 KB)reul 하나 잡고, geugeuro 읽고, 읽은 만큼만 쓰고, file kkeutkkaji 반복합니다.
Gamsungjeok-euro는, 호수reul son-euro deureollida haneun geot보다, 바가지로 물을 옮기는 geot과 비슷합니다. Hosuneun 안 들어갈 su 있지만(memory), 바가지는 botong 괜찮습니다.
import java.io.File
fun copyByChunks(from: File, to: File) {
from.inputStream().use { input ->
to.outputStream().use { output ->
val buffer = ByteArray(8 * 1024) // 8 KB
while (true) {
val read = input.read(buffer)
if (read < 0) break // EOF
output.write(buffer, 0, read) // write only what was read
}
}
}
}
Yeogiseo hana-ui 디테일 때문에 사람들의 세대가 부서졌고, 농담이 아닙니다. Majimak 단계에서 readneun jaru buffer 크기보다 작습니다. Mann약 output.write(buffer) cheoreom readreul 지정하지 않으면, 이전 읽기에서 남-eun “tail”reul sseuge 되어 filei 손상됩니다. Igeon, texteul boksahae 놓go kkeut에 uiyochi 않ge ijeon 대화 일부reul deopbutyeo beorineun geot과 같습니다 — awkward하고 의심스럽죠.
Chunk loop가 code-reul asynchronous하게 만들지는 않습니다
“chunks”ra-neun dan-eul deutgo, modeun geosi jadong-euro “async”ga 되고 “non-blocking”i 된다고 기대하는 saramdo 있습니다. Hajiman: InputStream.read()neun yeojeonhi threadreul blocking합니다. Dand, chunk loopga uri에게 두 가지 superpowerreul junda-neun geos.
Cheot jjae — control: uri-ga 이해하기 쉬운 loop 안에서 과jeong-eul 직접 제어합니다. Progressreul 계산할 su 있고, logreul 남길 su 있고, 속도를 재(원한다면) 잴 su 있고, 무엇보다 — 멈출 su 있습니다.
Dul jjae — cancellation point: iteration 사이에 isActivereul 확인(또는 ensureActive() 호출)hae, 취소됐다면 정상적으로 종료할 su 있습니다.
즉, chunk loop는 “accelerator”ga 아니라 “handle and brake”입니다. Geurigo 인류 역사ga 보여주듯, brake가 처음 생각보다 더 유용한 경우가 많습니다.
3. Cancellation points: isActive and ensureActive()
isActive로 확인
Ije coroutineeul 추가해 봅sida. Jungyo한 geot hana: withContext(...) 안에서는 lambda가 receiver로 CoroutineScopereul 가지므로, isActivereul 접근할 su 있습니다. isActive == false면 Jobi 취소되었다는 뜻이고, 이제 작업을 끝낼 ttae입니다.
Cheot “jeongjikhan” cancel 가능 버전은 최대한 직선적입니다: 취소됐다면 CancellationExceptioneul 던집니다. Igeon 표준 cancellation signal입니다.
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import java.io.File
suspend fun copyCancellable(from: File, to: File) {
withContext(Dispatchers.IO) {
from.inputStream().use { input ->
to.outputStream().use { output ->
val buffer = ByteArray(8 * 1024)
while (true) {
if (!isActive) throw CancellationException("Copy cancelled")
val read = input.read(buffer)
if (read < 0) break
output.write(buffer, 0, read)
}
}
}
}
}
Juyeui: checkga read() ijeone it습니다. Igeon 유일한 선택은 아니지만, botong 더 좋은 동작을 줍니다: cancellation이 iteration 사이에 들어오면, 불필요한 read/write를 시작하지 않습니다.
Dand, miracle-eun 약속하지 않습니다: cancellation이 blocking read() 수행 중에 들어오면, coroutineun read()ga return할 ttaekkaji 그 사실을 알 su 없습니다.
ensureActive()로 확인
if (!isActive) checkdo 괜찮지만, coroutine에는 더 깔끔해 보이는 스타일이 하나 더 있습니다: ensureActive(). Igeon 두 가지를 합니다: coroutine이 active인지 확인하고, 아니면 CancellationExceptioneul 대신 던져 줍니다.
Igeon 좋습니다. “noisy” codereul 덜 쓰게 되고, 의미가 더 잘 보입니다: “매 step 전에, 우리가 취소되지 않았는지 확인하라”.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import java.io.File
suspend fun copyCancellable2(from: File, to: File) {
withContext(Dispatchers.IO) {
val buffer = ByteArray(8 * 1024)
from.inputStream().use { input ->
to.outputStream().use { output ->
while (true) {
ensureActive() // throws CancellationException if cancelled
val read = input.read(buffer)
if (read < 0) break
output.write(buffer, 0, read)
}
}
}
}
}
Yeogiseo 철학을 이해하는 게 중요합니다: uri-neun cancellationeul “japneun” geosi 아니라 geuge wa hyeopryeokhamnida. Cancellationeun “disk error”ga 아니라 정상적인 scenario입니다.
4. CancellationException and error handling
Wae cancellationeul “mute”하면 안 될까요
Yeo tae exceptioneul “mwo-ga kkaejyeotda”ro만 봤다면, CancellationExceptioneun 세상 viewreul 조금 바kkul su 있습니다(좋은 의미로). I exceptioneun “opeureisyeoneul 일부러 멈chwo-seo”라는 뜻입니다.
Coroutineeseo i geot-eun cancellation로 인해 종료되는 표준 메커니즘입니다. Geuraeseo CancellationExceptioneun 특별한 위치를 가집니다: botong 사용자에게 ‘error’로 포장하지 말아야 하고, 무서운 stack trace를 찍을 필요도 없고, 더더욱 “amu il-do eopseotda” cheoreom 행동하면 안 됩니다.
초보가 하는 가장 위험한 실수는 ireon geos입니다: “na-neun modeun errorreul catch하니까 잘하고 있지”.
import kotlinx.coroutines.CancellationException
fun riskyCatchAll(block: () -> Unit) {
try {
block()
} catch (e: Exception) {
println("Oops, error: ${e.message}") // can accidentally swallow cancellation
}
}
Silmul coroutine codeeseo i 습관은 bugro 바뀝니다: Jobeul 취소했는데, 어딘가에서 CancellationExceptioneul 일반 Exceptioncheoreom 잡아버리고… 계속 일합니다. Igeon 전자레인지에서 “Stop”을 눌렀는데, 내부에서 누군가 “no-no, 우리는 그 버튼을 무시합니다”라고 말하는 것과 비슷합니다.
Olbareun style: “modeun exception”eul 잡는다면, CancellationException은 반드시 다시 던져야 합니다.
import kotlinx.coroutines.CancellationException
fun safeCatchAll(block: () -> Unit) {
try {
block()
} catch (e: CancellationException) {
throw e // cancellation is not an "error"; do not swallow it
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
suspend-function에서도 원칙은 같습니다: 어딘가에서 일반 catch를 한다면, cancellation을 존중해야 합니다.
5. Cancelling from outside and the execution scheme
Cancellable copy command
Gidaehaebopsida: file processing gyo-yuk용 console toolreul 계속 발전시키고 있다고(가정) 합시다(ireum-eul FileWorker라고 haebopsida). Copy commandga cancel 가능하길 원합니다.
Jageun utility function-euro 시작합시다: han file copyreul cancel 가능하게. Juyeui: “partial file”eul 어떻게 할지(rollback/deletion 등)는 오늘 주제가 아닙니다 — 오늘 목표는 consequences 정리가 아니라 “멈추는 것” 자체입니다(geugeun 별도 작업입니다).
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import java.io.File
suspend fun copyFileCommand(fromPath: String, toPath: String) {
val from = File(fromPath)
val to = File(toPath)
withContext(Dispatchers.IO) {
val buffer = ByteArray(8 * 1024)
from.inputStream().use { input ->
to.outputStream().use { output ->
while (true) {
ensureActive()
val n = input.read(buffer)
if (n < 0) break
output.write(buffer, 0, n)
}
}
}
}
}
I 예시의 핵심은 “modeun 상황을 위한 완벽한 copy utility”라는 게 아니라, 올바른 responsibility boundaryreul 보여 준다는 것입니다: blocking I/Oreul Dispatchers.IO로 분리할 su 있고, resource를 닫을 su 있고, 이제 cancellation이 “현실”이 되는 지점을 추가할 su 있습니다.
Job.cancel() and waiting for completion
Cancellation은 oebueseo taskreul 취소할 su 있을 ttae 비로소 유용해집니다: 예를 들어 timer, 사용자 명령, “program is closing” signal 등.
Console app에서 가장 단순한 scenario: coroutine에서 copyreul 시작하고, 조금 기다렸다가 취소합니다(현실에서는 “조금 기다렸다”가 “사용자가 Cancel을 눌렀다”로 바뀌겠죠).
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val job = launch {
copyFileCommand("data/big.bin", "data/big_copy.bin")
}
delay(50) // simulate "user changed their mind"
job.cancelAndJoin() // cancel and wait for completion
println("Copy stopped") // Copy stopped
}
Yeogiseo 두 가지가 중요합니다.
Cheot jjae, cancelAndJoin()eun “그냥 취소”ga 아니라 “취소하고, codega jinjja로 빠져나올 ttaekkaji 기다리기”입니다. 즉 use {} 안에서 resource가 닫히고, finallyga 있다면 geugeul 모두 마칠 ttaekkaji.
Dul jjae, 만약 copyFileCommand 안에 ensureActive()/isActivega eopseotdamyeon, cancellation이 “느껴지지” 않을 su 있습니다: coroutine이 file kkeutkkaji loopreul 계속 돌 수 있습니다(또는 다음 suspend point까지, 그런de blocking I/O에는 suspend pointga 없을 su도 있습니다).
Mini scheme: eodi-eseo cancellationeul “notice”하나
Gakkeum processreul jageun algorithmcheoreom bomyeon, 뇌가 cancellationeul “magical button”으로 착각하지 않게 도와줍니다. Geugeun 그저 적절한 위치에서 하는 check일 뿐입니다.
flowchart TD
A[Copy operation start] --> B[Open input/output via use]
B --> C{ensureActive / isActive?}
C -- cancelled --> D[Throw CancellationException]
C -- active --> E["read(buffer)"]
E --> F{EOF?}
F -- yes --> G[Exit loop]
F -- no --> H["write(buffer, 0, read)"]
H --> C
Yeogiseo 핵심 생각이 보입니다: ensureActive() 또는 isActive checkga eopseumyeon, blocking loop 안에서는 cancel()에 대한 “내장” 반응이 없습니다. Ban대로, check가 있으면 cancellation은 이해 가능하고, 재현 가능하며, 명확한 scenario가 됩니다.
6. Common mistakes
Mistake 1: “Cancellation does not work” — because there are no cancellation checks inside.
File opeureisyeoni while (true) gat-eun gin loop인데 isActive/ensureActive()ga eopdamyeon, job.cancel()ga jeuksi modeun geoseul 멈chul 의무는 없습니다. Blocking I/O에서는 cancellation이 자동으로 “붙지” 않습니다. Geuraeseo 규칙은 단순합니다: gin loop 안에는 coroutine active checkreul 주기적으로 추가하고, botong iteration당 한 번 둡니다.
Mistake 2: reading “all at once” via readBytes() and hoping for cancellation.
Fileeul 통째로 읽으면, 멈출 su 있는 제어 가능한 지점을 잃고, 큰 file에서는 memory risk도 커집니다. Ireul Dispatchers.IO로 옮겼더라도, 이런 스타일에서는 cancellation이 불편합니다: 읽기가 끝날 ttaekkaji 과정 제어가 거의 없습니다. Chunk loopga 두 문제를 한 번에 해결합니다.
Mistake 3: output.write(buffer) instead of output.write(buffer, 0, read).
Classic입니다. Majimak chunk는 거의 항상 buffer보다 작습니다. Buffer 전체를 쓰면 여분 byte를 덧붙여 결과가 깨집니다. File task에서 이런 bug는 특히 교활합니다: “file은 있는 것 같은데”, 내부는 쓰레기고, 종종 한참 뒤에야 발견됩니다.
Mistake 4: catching Exception and accidentally swallowing CancellationException.
Coroutine cancellation은 종종 CancellationException으로 구현됩니다. catch (e: Exception)를 쓰고 CancellationException을 다시 던지지 않으면, cancellation을 망칠 수 있습니다: 작업이 이미 취소됐는데도 계속 실행됩니다. Olbareun style은 CancellationException을 별도로 처리하고, 항상 다시 던지는 것입니다.
Mistake 5: expecting instant cancellation inside a blocking read().
ensureActive()ga 있어도 cancellation check는 여러분의 step 사이에서만 이루어집니다. 지금 당jang threadga read()에서 blocking 중이면, coroutine은 그 call 내부로 “teleport”해서 즉시 멈출 수 없습니다. 일반적인 disk 작업에서는 보통 감내할 수 있지만, model을 이해하는 게 중요합니다: 제어가 Kotlin code로 돌아오고, 다음 check에 도달했을 때 cancellation이 적용됩니다.
GO TO FULL VERSION