官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 炎陵县| 电白县| 永靖县| 太仓市| 涟水县| 顺义区| 保亭| 秭归县| 万盛区| 龙江县| 罗江县| 太原市| 麦盖提县| 麻栗坡县| 资兴市| 木里| 宜春市| 梅州市| 加查县| 赤峰市| 五寨县| 淄博市| 都江堰市| 道孚县| 新营市| 闸北区| 增城市| 双峰县| 镇康县| 和静县| 子长县| 昭通市| 旬阳县| 玛纳斯县| 吐鲁番市| 长宁县| 桐柏县| 绥江县| 金乡县| 镇江市| 嘉荫县|