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

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.

主站蜘蛛池模板: 杂多县| 萝北县| 泾川县| 宣恩县| 延长县| 安顺市| 栾城县| 图木舒克市| 东海县| 九江县| 满洲里市| 呼和浩特市| 凤山市| 蓬安县| 中江县| 南康市| 库车县| 珠海市| 屯留县| 桦南县| 清涧县| 永安市| 高邑县| 望城县| 肥乡县| 霍山县| 夹江县| 甘谷县| 广平县| 宝坻区| 霍州市| 莱州市| 新津县| 阿克| 安徽省| 大洼县| 南陵县| 绥棱县| 肥乡县| 集贤县| 专栏|