- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 238字
- 2021-08-05 10:46:43
Deadlocks
Often, in order to guarantee that concurrent code is synchronized correctly, it's necessary to suspend or block execution while a task is completed in a different thread. But due to the complexity of these situations, it isn't uncommon to end up in a situation where the execution of the complete application is halted because of circular dependencies:
lateinit var jobA : Job
lateinit var jobB : Job
fun main(args: Array<String>) = runBlocking {
jobA = launch {
delay(1000)
// wait for JobB to finish
jobB.join()
}
jobB = launch {
// wait for JobA to finish
jobA.join()
}
// wait for JobA to finish
jobA.join()
println("Finished")
}
Let's take a look at a simple flow diagram of jobA.

In this example, jobA is waiting for jobB to finish its execution; meanwhile jobB is waiting for jobA to finish. Since both are waiting for each other, none of them is ever going to end; hence the message Finished will never be printed:

This example is, of course, intended to be as simple as possible, but in real-life scenarios deadlocks are more difficult to spot and correct. They are commonly caused by intricate networks of locks, and often happen hand-in-hand with race conditions. For example, a race condition can create an unexpected state in which the deadlock can happen.
- Oracle從入門到精通(第3版)
- SpringMVC+MyBatis快速開發與項目實戰
- 青少年美育趣味課堂:XMind思維導圖制作
- RTC程序設計:實時音視頻權威指南
- Redis Essentials
- C語言程序設計
- Hands-On Neural Network Programming with C#
- App Inventor少兒趣味編程動手做
- The Statistics and Calculus with Python Workshop
- 算法秘籍
- Xamarin Cross-Platform Development Cookbook
- WordPress Search Engine Optimization(Second Edition)
- 分布式數據庫HBase案例教程
- 用Python動手學統計學
- 計算機應用基礎(Windows 7+Office 2010)