- Mastering High Performance with Kotlin
- Igor Kucherenko
- 256字
- 2021-06-25 20:55:23
The problem of concurrency and parallelism
While concurrency is executing independent subtasks out of order without affecting the final result, parallelism is the executing subtasks that are carried out simultaneously. Parallelism involves concurrency, but concurrency is not necessarily executed in a parallel manner.
The compiler feels free to reorder instructions to perform optimization. This means that there are cases in which accesses to variables, during the execution of a program, may differ from the order specified in the code. Data is moved between registers, caches, and RAM all the time. There are no requirements for the compiler to perform synchronization between threads perfectly because this would cost too much from the performance point of view. This leads to cases when different threads may read different values from the same shared variable. A simplified example of the case described here may look like this:
fun main(vars: Array<String>) {
var sharedVariableA = 0
var sharedVariableB = 0
val threadPool = Executors.newFixedThreadPool(10)
val threadA = Runnable {
sharedVariableA = 3
sharedVariableB = 4
}
val threadB = Runnable {
val localA = sharedVariableA
val localB = sharedVariableB
}
threadPool.submit(threadA)
threadPool.submit(threadB)
}
In a body of the threadB thread, the value of the localA variable is 3, and the value of the localB variable is 4. But if the compiler reorders the operations, the final values of the local variables may differ. To get a better understanding of this issue, we need some knowledge of the internal system of the Java Memory Model.
- VMware View Security Essentials
- 復雜軟件設計之道:領域驅動設計全面解析與實戰
- C++面向對象程序設計(微課版)
- 華為HMS生態與應用開發實戰
- Developing Middleware in Java EE 8
- MATLAB 2020 從入門到精通
- MySQL數據庫基礎實例教程(微課版)
- Oracle JDeveloper 11gR2 Cookbook
- 學習正則表達式
- 從零開始學Linux編程
- 小程序,巧應用:微信小程序開發實戰(第2版)
- Instant PHP Web Scraping
- R數據科學實戰:工具詳解與案例分析
- 編寫高質量代碼:改善Objective-C程序的61個建議
- Python程序設計與算法基礎教程(第2版)(微課版)