1. Dispatchers: korutina-ga eodi, eotteon geos-e seo silhaengdoenun-ga
Korutin-eul cheoeum alge doemyeon jaju sunjinhan gidae-ga saenggimnida: “O, korutin-iran geon geunyang seuseuro ttokttokhage ppalli doeneun geo-go, seuredeu-neun nawa sanggwan eopgetji.” Hajiman yugan — seuredeu-neun nuguege-na gwallyeondoemnida. Danji daebubun-eun jal an boill ppun-imnida. Dispatchers neun “yeok-e issneun dipaecho” cheoreom saenggakhamyeon doemnida: nae korutin-eul eotteon “peullaetpom” (eotteon seuredeu pul) e 올려 silhaenghalji jeonghaeseo, dareun il-e banghae doiji anhge, tto udoehan il-eul ha게 ha 줍니다.
Meoritsoge hangsang du gaji reul bunrihae dwo야 합니다: korutina neun jeongji-haetda-ga dasi 이어갈 su itneun gayeoun jageob, seuredeu neun silje-ro kode-ga silhaengdoeneun mug-eoun OS jaryowon-imnida. Kotlin-eun suspend 로 korutin-eul eoneo-ui il-bu로 mandeul-eotjiman, daebubun-ui “mekanikeu” neun kotlinx.coroutines ra neun raibeureori-e issseumnida. 즉, keompailleo-ga modeun geol haegyeolhaejuneun “magia” ga anira, keun teukjing-eun “raibeureori-e issneun ttokttokhan 함수 wa 타입” e gabseumnida.
Mini table: eoneu Dispatcher reul eonje sseuneun-ga
| Dispatcher | Botong eonje sayonghaneun-ga | Gandanhan han-jul saenggak |
|---|---|---|
|
gyesan (CPU), deiteo cheori, jeongnyeol, kyesan/jeongbo hap산 | “Du뇌-ga gyesan한다” |
|
beulloking I/O: pa-il, neteuwokeu, DB (JDBC), gidarim-i saenggil su inneun modeun il | “Son-i gidarigo ilggo/ssunda” |
|
deuksub/teuksu 케이스; 초보자에게는 botong piryohaji anheum | “Geunyang isanghage 둬라” |
Oneul-eun silje-ro du gaji-myeon chungbunhamnida: Default wa IO.
Dispatchers.Default: CPU gyesan-eul wihan
Dispatchers.Default reul “ju-yo-hago man능-in geot” 으로 jeonghage sip-eojimnida. ireum-i “default” ra seo “gibon값” cheoreom deulligi ttaemun-ibnida. Hajiman Default ui uimi-neun “man능” i anira, CPU jageob-eul wihan hapseorijeog-in seuredeu pul imnida: silje-ro gyesan 하고, 필터링 하고, 그룹화 하고, bogoseo reul mandeulgo, munja열-eul gajeonghago, memori 안에서 JSON-eul cheorihago 하는 deung, gyesan-e gakkeun il-deul-imnida.
Yuhanhaneun sawon su-ga inneun 사무실-eul sangsanghaeboseyo. Dispatchers.Default neun bunseok-ga deul-i issneun buseom 입니다. in-won-eun manhji 않고, gyesan jageob-e jibhjunghaeya 합니다. geureonde bunseok-ga deul-e게 프린터 앞에서 chulryeok-eul gidarige (즉, beulloking opeureisyeon-eul 하게) 하면 사무실-eun geupgyeokhi 느려집니다: bunseok-ga deul-eun gidarim-e 묶이고, gyesan-eun meomchub니다.
Gandanhan 진단-eul bopsida: hyeonjae seuredeu ireum-eul chulryeokhagi.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
launch(Dispatchers.Default) {
println("Default: " + Thread.currentThread().name)
}
}
Yeogi서 "DefaultDispatcher-worker-1" cheoreom bo일 geot-imnida (guchi-jeog-in ireum-eun hwangyeong-e ttara dallajimnida). geuge 바로 Default pul e soghan “worker” seuredeu 입니다.
Dispatchers.IO: beulloking I/O reul wihan
Pa-il-eul ilk거나 ssugo, JDBC 로 DB-e jeobgeunhageona, neteuwokeu 요청-eul 보내면 (“겨우 200 ms” 라 하더라도) daebubun-eun “gyesan” i anira gidarim imnida. korutin-e게는 geuge jeong상 이지만, munje-neun korutin-e issneun 게 아니라 eoneu seuredeu eseo gidarim-eul 하고 inne냐 에 있습니다.
Dispatchers.IO neun baro geureon jageob-eul wihan seuredeu pul 입니다. aidee-neun ireon geot 입니다: “gidarim-eul Default 에서 son-e gajang gwi한 CPU seuredeu-reul ppaeatjji malja.” i geosi kode-reul “jariseuro ppalli” hage mandeulji-neun 않지만, aep을 buh-a-reul badado 안정적 으로 mandeureo jup니다: jageob-i manh-eul ttae “gidarim” i “gyesan” eul millyeo내지 않게 됩니다.
Dasi seuredeu ireum-eul bopsida:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
launch(Dispatchers.IO) {
println("IO: " + Thread.currentThread().name)
}
}
Botong "DefaultDispatcher" ga deureoganneun ireum-eul boge doego, ttaeron "IO" pul-gwa gwallyeondoen ireum-eul boge doemnida (kotlinx.coroutines guhyeon-e 따라 비슷하게 bo일 su itsseumnida). uri-ga jung요하게 bol geos-eun “ireum munja열” i 아니라 aidee 자체 입니다: neoga 명시적으로 “igeon I/O” 라고 말한 geot입니다.
Dispatcher-neun eodi-eseo jeonghaneun-ga
초보자-neun ttaeron setDispatcherForAllCoroutinesToIO() cheoreom “jeon-yeok seoljeong” 버튼-eul chajseumnida. geureon 버튼-eun eopseumnida (geurigo geuge deo johseumnida: geureom peurojekteu-ga “mwo든 IO로, geuraeya doeni깐” seuta-il-i doel 테니까요). Gibon korutin kode-eseo dispatcher-neun korutin-eul sileung 하는 geu jari 에서 jeongha집니다: launch(...) 또는 async(...).
Naran히 boryeojugesseumnida:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
launch(Dispatchers.Default) {
println("Compute on: " + Thread.currentThread().name)
}
launch(Dispatchers.IO) {
println("IO on: " + Thread.currentThread().name)
}
}
Gageukseong-eul wihan jungyo han 습관: neoga Dispatchers.IO reul boge doemyeon, beulloking gidarim (pa-il/neteuwokeu/DB) 을 ye상하게 됩니다. Dispatchers.Default reul boge doemyeon gyesan-eul ye상합니다. i geon tim nae “yak속” 처럼, nam-ui kode-reul ilge doegi 쉽고, prod-eseo nangamhan sorpresa-ga jul어듭니다.
2. Silsu: Dispatchers.Default reul beullokinghagi
Jigeum-buteo jogeum apado, yu익한 yaegi-reul ha겠습니다: korutin-eun 물리/physics-reul eopsaege 못합니다. korutin an-eseo Thread.sleep(1000) eul ha면, silje-ro seuredeu-reul ja게 만듭니다. geuge Dispatchers.Default pul-ui seuredeu 라면, gyesan해야 할 “bunseok-ga” 를 ja게 만드는 것 입니다.
Nappeun 예 (kompail-eun do지만, uimi-jeog-euro yuh해요):
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
launch(Dispatchers.Default) {
Thread.sleep(200) // Default pul-ui seuredeu-reul beulloking
println("Woke up on Default")
}
}
Korutin an-eseo “jamsi meomchum” i piryohada면, 올바른 jamsi meomchum-eun delay(...) 입니다 (ijeon 강의에서 다뤘습니다). geureom korutin-eun 일시정지되고, seuredeu-neun gulsokhi 놀 필요가 없습니다.
Banmyeon silje-ro beulloking opeureisyeon-eul bu르는 경우 (ye: gubon API 로 pa-il ilgi, teukbyeolhan 어댑터 없은 JDBC), geuraedo jeog-eo도 Dispatchers.IO 에서 silhaenghaneun geot-i joh습니다.
Jogeum deo 솔직한 버전: “beulloking 호출이지만, 적어도 올바른 jari에서”:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
launch(Dispatchers.IO) {
Thread.sleep(200) // yeojeonhi beulloking, hajiman 적어도 Default-neun 아님
println("Blocked IO, not Default")
}
}
Ireon geot-i “wanbyeokhan asinkeuron segye” 는 아니지만, gyesan pul-e daehae seo-neun 훨씬 덜 yuh해집니다.
3. Silsu: konsol aep peurogeuraem-eseo GlobalScope sayonghagi
GlobalScope neun mae우 yuhokjeog 입니다. teukhi “modeun geot-i 컨텍스트-reul 요구한다” 는 geot-e 지쳤다면 더 그렇습니다. silje-ro “eodi서든” korutin-eul si작할 su itsge 해줍니다. Hajiman geu pyeonriham-e daehae dae가-ro, konsol aep (geurigo geugeppunman-i 아니라) e서는 jaju ireon sanghwang-e ppajimnida: main 함수-ga kkeutnatneunde, korutin-eun ajik amugeotdo 못했다.
즉, println eul sseotneunde “eotteol ttaen 찍히고, eotteol ttaen 안 찍힌다.” cham joh-eun “샤먼 체험” i지만, peurogeuraem-eul sseuneun bangbeop-euroseoneun najseumnida.
Munje-reul 의도적으로 deureonaeneun 예:
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@OptIn(DelicateCoroutinesApi::class)
fun main() {
GlobalScope.launch {
delay(100)
println("Maybe printed, maybe not")
}
// main-eun baro kkeutnam: korutin-i 못 kkeutnael su도 있음
}
@OptIn(DelicateCoroutinesApi::class) eul jujahae boryeoseyo. Igeon geunyang gwangnyeomjeog jeolchaneun 아닙니다: raibeureori-ga geumseong-euro “joshimhae라, igeon delicate (min감/wiheom)” 라고 말해줍니다. GlobalScope ui aidee-neun, korutin-i “geoui 데몬 cheoreom” sal-a, nuga 소유ja인지 명확하지 않고, nuga kkeuteul 보장haeneunji도 불명확해진다는 점입니다.
Oneul-ui 범위와 konsol peurogeuraem-eseo ui gibon 규칙-eun gandan합니다: runBlocking 안에서 korutin-eul si작 해서, main i 시나리오 kkeut-eul jeongjik하게 gidar리게 하세요.
Hyeonjae sujun-eseo ui 올바른 스타일:
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
launch {
delay(100)
println("Printed for sure")
}
}
Deo gogeup-ui korutin saengmyeong-ju gi-gan gwa-li bangbeop-eun ajik 배운 적이 없고 (oneul-do 다루지 않을 겁니다). geuraeseo “hana-ui jin입점, 통제된 종료” 를 잡고 갑니다.
4. Silsu: Deferred eseo await() reul ppaetneun geot
async neun Deferred<T> reul banhwan합니다. igeon T ga 아닙니다. igeon “언젠가 T reul jul keonteineo” 입니다. 그리 고 await() reul 하지 않으면, 결과는 없습니다. Gajang jaju natananeun 형태는 Deferred reul “이미 숫자/munja열” in geot cheoreom sayong하려는 시도입니다.
Uidojeog-euro daebihae bopsida:
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val d = async { 40 + 2 }
println(d) // DeferredCoroutine{Active}@...
println(d.await()) // 42
}
Chulryeok-e DeferredCoroutine{Completed} cheoreom bo-in다면, geuge “teull린 chulryeok” i 아닙니다. neoga “결과” ga 아니라 “wrapping 객체” reul chulryeokhan geot입니다.
Wae jaju await jeon-e yeoreo gae-ui async reul meonje si작haneun-ga
Gajang jeontongjeog-in 논리: “du gyesan-eul byeongnyeol-ro si작haego, 나중에 둘 다 gidar리지.” 만약 cheot beonjjae async 직후-e baro await() reul 해버리면, “멈춰, cheot beonjjae kkeutnal ttaekkaji gidar릴게. du beonjjae-neun 그 다음에” 라고 말하는 것과 같습니다. ttaeron geureohge haeya 하지만, jaju byeongnyeol si작-ui uimi-reul ileobeor립니다.
Ol바른 “먼저 si작 — 나중에 gidar림” 예:
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val a = async { delay(100); 10 }
val b = async { delay(100); 32 }
val sum = a.await() + b.await()
println("sum = $sum") // sum = 42
}
Yeogi서는 두 jageob-eul 모두 si작한 뒤에 gidar림이 일어납니다.
5. Mini scenario: BudgetBuddy wa byeongnyeol bogoseo
Ireon geot-i “yeok-gwa dipaecho” gwanhan sun수한 이론-euro만 namji 않게, 이미 jichul gwanri konsol aep-i 있다고 sangsanghaebopseumnida (ireum-eun BudgetBuddy 라고 haejyo). 예전에는 geu aep-i nae역-eul jeojang하고, 필터링하고, bogoseo-reul 만들고, 결과를 chulryeok할 줄 알게 되었습니다. ije-neun, 예를 들어 du gae-ui bogoseo — “카테고리별 합계” 와 “지출 top” — reul gyesan해서, silje-ro byeongnyeol-ro 처리하고 싶습니다. hyeonsil-eseo bogoseo-neun (deiteo-ga manh-go, geulup-ing-i manh-a) 무거울 su 있기 때문입니다.
“긴 jageob” 을 delay 로 흉내내는 두 gae-ui suspend 함수-reul 만들겠습니다. 요점-eun 지연 시간이 아니라 구조입니다: eotteon jageob-eul Default 에 올릴지, 그리고 결과를 eotteoke 깔끔하게 모을지.
import kotlinx.coroutines.delay
suspend fun calcTotalsReport(): String {
delay(120)
return "Totals: food=1200, rent=30000"
}
suspend fun calcTopReport(): String {
delay(150)
return "Top: rent=30000, laptop=80000"
}
Ije Dispatchers.Default 에서 실행합니다 (“gyesan” 이라고 가정; 예제에서는 delay ga 들어있지만):
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val totals = async(Dispatchers.Default) { calcTotalsReport() }
val top = async(Dispatchers.Default) { calcTopReport() }
println(totals.await()) // Totals: food=1200, rent=30000
println(top.await()) // Top: rent=30000, laptop=80000
}
Yeogi서 du 가지 원칙이 한 번에 bo입니다: GlobalScope reul sseuji 않고 runBlocking 안에서 saenghwal한다; 그리고 await() reul ppaetji 않는다. uri-e게 piryohan geon bogoseo munja열이지, “munja열-eul jun다는 약속” i 아니기 때문입니다.
6. Nuance: dispatcher-neun kode-reul ppalli haji 않는다
Dispatchers reul “seongneung tuing” 처럼 da루기 쉬운데요: Dispatchers.IO reul ju면 ppalli jina? Default reul ju면 ro켓? Hyeonsil-eseo Dispatchers neun “sokdo” boda saengjonseonggwa 예측 가능성 e gakkaun 개념입니다.
Jageob-i CPU-bound 라면 Dispatchers.IO 에서도 ppalli jiji 않습니다: danji dareun seuredeu pul-eul deo sseuge 될 뿐입니다. jageob-i beulloking이라면 Dispatchers.Default 에서도 non-blocking-i do지 않습니다: danji jung요한 worker seuredeu-reul beulloking할 뿐입니다. i uimi-eseo dispatcher-neun turbog-buteon-i 아니라, nae 일-eul 올바른 “seonban” e 올리는 선택입니다.
Meoritsoge gajang gan단한 seukima reul dwo두면 pyeon합니다:
flowchart TD
A["launch/async: korutin sijak"] --> B{"Eotteon jageob?"}
B -->|CPU/gyesan| C["Dispatchers.Default"]
B -->|Beulloking I/O| D["Dispatchers.IO"]
C --> E["Gyeolgwa/chulryeok"]
D --> E["Gyeolgwa/chulryeok"]
Bun-gi-reul 잘못 골랐을 ttae, kode-ga “jageun deiteo” 에서는 dongjak하다-ga, deiteo-ga 커지면 gapjagi seongneung-i degreideu 될 su 있습니다.
7. Tipjeogin silsu wa jungsang
Sil su 1: “geunyang swipda” neun iyuro konsol aep-eseo GlobalScope reul sseuneun geot.
Jungsang-eun botong sinbirop습니다: “eotteol ttaen 찍히고 eotteol ttaen 안 찍혀요”, “eotteol ttaen pa-il-i sseojyeotgo eotteol ttaen an sseojyeosseoyo”, “na-neun modeun geot-i dongjakha-neunde main kkeut-e Thread.sleep(...) reul 넣어야만 해요.” munje-neun main i korutin-i kkeutnagi jeon-e kkeutna버린다는 점입니다. chiryobeop-eun “gyeorjeong” 입니다: runBlocking 시나리오 안에서 korutin-eul si작해 종료 지점을 통제 가능하게 만들고, uiyeon-e 맡기지 마세요.
Sil su 2: await() reul ppaetgo Deferred<T>reul T cheoreom 다루는 geot.
Jungsang-eun deo “teknikal” 합니다: DeferredCoroutine{Active} cheoreom isanghan munja열-i chulryeok되고, 타입이 맞지 않으며, keompailleo-ga wae Deferred<Int> 와 Int reul 더하려고 하냐고 불평합니다. chiryobeop-eun gandan합니다: async 는 “gyeolgwa-ui yaksok”, await() 는 geu yaksok-eul silje 값으로 바꾸는 시점임을 기억하세요 (그리고 geu gidar림도 suspend opeureisyeon입니다).
Sil su 3: korutin an-eseo seuredeu-reul beullokinghago “korutin-i modeun geol 고쳐줄 거야” 라고 생각하는 geot.
Gajang pyeonhan jungsang-eun peurogeuraem-i “meomchuneun geot cheoreom” bo이거나, 여러 jageob-eul si작하면 isang하게 느려지는 geot입니다. jaju ui geunwon-eun Thread.sleep(...), beulloking ilgi/ssugi, 또는 “mugeoun 호출” 을 silsu-ro Dispatchers.Default 에 올린 geot입니다. chiryobeop-eun du dan-gye입니다: cheotjjae, “jamsi meomchum” e delay(...) reul sseugo Thread.sleep(...) reul sseuji 마세요; duljjae, beulloking I/O 호출-eun Dispatchers.IO 에서 silhaeng해 gyesan pul-ui seuredeu-reul 빼앗지 않게 하세요.
Sil su 4: Dispatchers reul “sokdo up” 도구로 boji 말고, silhaeng jari seontaek-euro boji 않는 geot.
Igeon segye-gwan silsu-jiman, silje munje-ro 이어집니다: gyesan-e daehae “random하게” IO reul put이고, modeun geot-e Default reul put여서, kode-ga seolmyeong bulganeung해집니다. chiryobeop-eun 습관입니다: “na-neun 지금 gyesan한다 (Default)” 또는 “na-neun 지금 gidar린다/ilg는다/ssunda (IO)” 라고 말해보세요. jeongjik하게 eotteon jageob인지 답할 su 없다면, geu kode-neun 아마 함수로 나누고 이름을 더 명확히 해야 합니다.
GO TO FULL VERSION