- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 376字
- 2021-08-05 10:46:43
Race conditions
Race conditions, perhaps the most common error when writing concurrent code, happen when concurrent code is written but is expected to behave like sequential code. In more practical terms, it means that there is an assumption that concurrent code will always execute in a particular order.
For example, let's say that you are writing a function that has to concurrently fetch something from a database and call a web service. Then it has to do some computation once both operations are completed. It would be a common mistake to assume that going to the database will be faster, so many people may try to access the result of the database operation as soon as the web service operation is done, thinking that by that time the information from the database will always be ready. Whenever the database operation takes longer than the webservice call, the application will either crash or enter an inconsistent state.
A race condition happens, then, when a concurrent piece of software requires semi-independent operations to complete in a certain order to be able to work correctly. And this is not how concurrent code should be implemented.
Let's see a simple example of this:
data class UserInfo(val name: String, val lastName: String, val id: Int)
lateinit var user: UserInfo
fun main(args: Array<String>) = runBlocking {
asyncGetUserInfo(1)
// Do some other operations
delay(1000)
println("User ${user.id} is ${user.name}")
}
fun asyncGetUserInfo(id: Int) = async {
user = UserInfo(id = id, name = "Susan", lastName = "Calvin")
}
The main() function is using a background coroutine to get the information of a user, and after a delay of a second (simulating other tasks), it prints the name of the user. This code will work because of the one second delay. If we either remove that delay or put a higher delay inside asyncGetUserInfo(), the application will crash. Let's replace asyncGetUserInfo() with the following implementation:
fun asyncGetUserInfo(id: Int) = async {
delay(1100)
user = UserInfo(id = id, name = "Susan", lastName = "Calvin")
}
Executing this will cause main() to crash while trying to print the information in user, which hasn't been initialized. To fix this race condition, it is important to explicitly wait until the information has been obtained before trying to access it.
- JavaScript前端開發模塊化教程
- NLTK基礎教程:用NLTK和Python庫構建機器學習應用
- PHP+MySQL+Dreamweaver動態網站開發實例教程
- HTML5+CSS3+JavaScript Web開發案例教程(在線實訓版)
- Nexus規模化Scrum框架
- Java EE 8 Application Development
- Mastering openFrameworks:Creative Coding Demystified
- OpenStack Networking Essentials
- 區塊鏈架構之美:從比特幣、以太坊、超級賬本看區塊鏈架構設計
- 零基礎學C語言(第4版)
- 算法訓練營:海量圖解+競賽刷題(入門篇)
- 趣味掌控板編程
- Access 2010數據庫教程(微課版)
- Visual C++網絡編程教程(Visual Studio 2010平臺)
- 嵌入式網絡編程