- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 240字
- 2021-08-05 10:46:44
Being explicit
Concurrency needs to be thought about and designed for, and because of that, it's important to make it explicit in terms of when a computation should run concurrently. Suspendable computations will run sequentially by default. Since they don't block the thread when suspended, there's no direct drawback:
fun main(args: Array<String>) = runBlocking {
val time = measureTimeMillis {
val name = getName()
val lastName = getLastName()
println("Hello, $name $lastName")
}
println("Execution took $time ms")
}
suspend fun getName(): String {
delay(1000)
return "Susan"
}
suspend fun getLastName(): String {
delay(1000)
return "Calvin"
}
In this code, main() executes the suspendable computations getName() and getLastName() in the current thread, sequentially.
Executing main() will print the following:

This is convenient because it's possible to write non-concurrent code that doesn't block the thread of execution. But after some time and analysis, it becomes clear that it doesn't make sense to have getLastName() wait until after getName() has been executed since the computation of the latter has no dependency on the former. It's better to make it concurrent:
fun main(args: Array<String>) = runBlocking {
val time = measureTimeMillis {
val name = async { getName() }
val lastName = async { getLastName() }
println("Hello, ${name.await()} ${lastName.await()}")
}
println("Execution took $time ms")
}
Now, by calling async {...} it's clear that both of them should run concurrently, and by calling await() it's requested that main() is suspended until both computations have a result:

- .NET之美:.NET關(guān)鍵技術(shù)深入解析
- C語(yǔ)言程序設(shè)計(jì)案例教程(第2版)
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設(shè)計(jì)
- WordPress Plugin Development Cookbook(Second Edition)
- Flutter跨平臺(tái)開(kāi)發(fā)入門(mén)與實(shí)戰(zhàn)
- Swift細(xì)致入門(mén)與最佳實(shí)踐
- ServiceNow:Building Powerful Workflows
- Web性能實(shí)戰(zhàn)
- 寫(xiě)給大家看的Midjourney設(shè)計(jì)書(shū)
- MATLAB 2020 GUI程序設(shè)計(jì)從入門(mén)到精通
- Java Web入門(mén)很輕松(微課超值版)
- A/B 測(cè)試:創(chuàng)新始于試驗(yàn)
- Activiti權(quán)威指南
- 物聯(lián)網(wǎng)軟件架構(gòu)設(shè)計(jì)與實(shí)現(xiàn)
- R語(yǔ)言入門(mén)與實(shí)踐