코틀린은 스레드 생성 과정을 단순화해서 쉽고 간단하게 스레드를 생성할 수 있다. 지금은 단일 스레드만으로도 충분하지만, 이후 과정에서는 CPU 바운드와 I/O 바운드 작업을 모두 효율적으로 수행하기 위해 스레드 풀도 생성할 것이다.
CoroutineDispatcher
코틀린에서는 스레드와 스레드 풀을 쉽게 만들 수 있지만 직접 엑세스하거나 제어하지 않는다는 점을 알아야 한다.
여기에서는 스레드를 하나만 갖는 CoroutineDispatcher를 생성할 것이며, 거기에 추가하는 모든 코루틴은 그 특정 스레드에서 실행된다. 그렇게 하려면 단 하나의 스레드만 갖는 CoroutineDispatcher를 확장한 ThreadPoolDispatcher를 생성한다.
fun main(args: Array<String>) = runBlocking {
val task = GlobalScope.async {
doSomething()
}
task.join()
println("Completed")
}
fun doSomething() {
throw UnsupportedOperationException("Can't do")
}
if (task.isCancelled) {
val exception = task.getCancellationException()
println("Error with message: ${exception.cause}")
} else {
println("Success")
}
fun main(args: Array<String>) = runBlocking {
val task = GlobalScope.async {
doSomething()
}
// This code will have the exception be propagated
task.await()
println("Success")
}
fun main(args: Array<String>) = runBlocking {
val task = GlobalScope.launch {
doSomething()
}
// This code will have the exception be propagated
task.join()
println("Success")
}
fun main(args: Array<String>) = runBlocking {
val dispatcher = newSingleThreadContext(name = "ServiceCall")
val task = GlobalScope.launch(dispatcher) {
doSomething()
}
// This code will have the exception be propagated
task.join()
println("Success")
}