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

Synchronization

As we already know, the JMM is a simplified model of the hardware memory architecture. If a variable is used frequently, it can be copied to the CPU cache. If several threads have a shared variable, then several CPU caches have their own duplicate of this variable. This is needed to increase access speed to variables. The hardware memory architecture has a hierarchy that is illustrated in the following diagram:

When several caches have duplicates of a variable that's stored in the main memory, the problem with visibility of shared objects may occur. This problem is referred to as a data race. This is a case when two or more threads change the values that were copied to caches. But one thread doesn't know about changes that were applied to the copied value by another thread. And when the thread updates the original variable in the main memory, the value that was assigned to the shared object by another thread can be erased. 

The following example clarifies the described case. Two threads run on two CPUs at the same time. And they have a shared object with the count variable that's been copied to caches of both CPUs. Both threads increment the copied values at the same time. But these changes aren't visible to each other because the updates haven't been flushed back to the main memory yet. The following diagram illustrates this:

To solve the problem with synchronization, you can use the volatile keyword, synchronized methods, or blocks, and so on. But all of these approaches bring overhead and make your code complex. It's better just to avoid shared mutable objects and use only immutable objects in a multithreading environment. This strategy helps keep your code simple and reliable.

主站蜘蛛池模板: 尚义县| 沙雅县| 隆化县| 三亚市| 汝城县| 唐山市| 建湖县| 贡觉县| 丰原市| 闵行区| 太康县| 澜沧| 崇义县| 霍邱县| 鄂尔多斯市| 巴青县| 台江县| 元朗区| 太仓市| 保靖县| 仙游县| 尉氏县| 沙洋县| 巩义市| 芜湖县| 赞皇县| 宁明县| 增城市| 双柏县| 鸡西市| 阿鲁科尔沁旗| 阿鲁科尔沁旗| 启东市| 紫云| 定边县| 巴彦淖尔市| 简阳市| 璧山县| 扎鲁特旗| 深水埗区| 开鲁县|