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

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.

主站蜘蛛池模板: 上杭县| 宁远县| 土默特左旗| 晋城| 永安市| 遂平县| 赤水市| 财经| 贡山| 抚顺县| 西青区| 搜索| 贵南县| 三河市| 拉萨市| 兴隆县| 保亭| 融水| 自贡市| 汉寿县| 衢州市| 瑞金市| 武安市| 蕲春县| 柳林县| 平利县| 谷城县| 公主岭市| 额尔古纳市| 武山县| 柳州市| 安塞县| 新泰市| 汉阴县| 休宁县| 博白县| 图片| 新余市| 彭州市| 宜兰市| 阿拉善左旗|