- 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.
- C及C++程序設(shè)計(第4版)
- 演進(jìn)式架構(gòu)(原書第2版)
- 精通搜索分析
- JavaScript入門經(jīng)典
- 區(qū)塊鏈底層設(shè)計Java實戰(zhàn)
- Getting Started with Eclipse Juno
- Django 3.0入門與實踐
- Python大學(xué)實用教程
- RESTful Web Clients:基于超媒體的可復(fù)用客戶端
- Oracle實用教程
- 基于GPU加速的計算機(jī)視覺編程:使用OpenCV和CUDA實時處理復(fù)雜圖像數(shù)據(jù)
- 計算語言學(xué)導(dǎo)論
- 深入淺出 HTTPS:從原理到實戰(zhàn)
- 精益軟件開發(fā)管理之道
- C語言編程魔法書:基于C11標(biāo)準(zhǔn)