线程缓存和Java内存模型

线程缓存和Java内存模型

本文介绍了线程缓存和Java内存模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解Java内存模型和线程。按照我的理解,每个线程都有一个主内存的本地副本。因此,如果一个线程试图改变一个 int 变量,例如某个对象,它将缓存 int 变量,然后如果它改变它,其他线程可能看不到更改。但是如果线程缓存一些对象而不是int?在这种情况下什么线程缓存它?如果线程缓存对对象的引用,则对其他线程不可见的任何对对象状态的更改?为什么?



预先感谢您

解决方案

缓存L1,L2,L3。每个CPU(也可能是CPU Core)都有自己的缓存。这缓存存储最小的主内存(RAM)集性能。

  _______________ ______________ 
| CPU 1 | | CPU 2 |
| _________ | | _________ |
| | 1级| | | | 1级| |
| |缓存| | | |缓存| |
| | | | | | | |
| | _________ | | | | _________ | |
| _______________ | | ______________ |
| | | |
| | | |
_ | _ | ______________ | _ | __
| |
|主存储器|
| _______________________ |


时间命令CPU 1(缓存)CPU 2(缓存)主内存
------- ---------- --- ------------- -------------- -------------
1 --- - - --- x = 10
2读取x(在cpu1上)x = 10 --- x = 10
3写入x 4读取x(在cpu2上)x = 20 x = 10 x = 10
5将缓存放到主内存x = 20 x = 10 x = 20

例如,上面的执行顺序,CPU2上的x值是错误的。 x值已由CPU1更改。
如果将x变量定义为易失性,则所有写入操作会立即反映到主存储器中。

I'm trying to understand the Java memory model and threads. As fas has I understand, each thread has a local copy of the "main" memory. So if one thread tries to change an int variable, for example, of some object, it caches the int variable and if it changes it, other thread might not see the change. But what if threads cache some object instead of int? What threads cache it in this case? If a thread caches a reference to an object any change to the state of the object are not visible to other threads? Why?

Thank you in advance

解决方案

CPU have different level caches L1, L2, L3. Every CPU (and also /may CPU Core) has own cache. This caches store minimal set of main memory (RAM) for performance.

  _______________    ______________
 |     CPU 1     |  |     CPU 2    |
 |   _________   |  |   _________  |
 |  | Level 1 |  |  |  | Level 1 | |
 |  |   Cache |  |  |  |  Cache  | |
 |  |         |  |  |  |         | |
 |  |_________|  |  |  |_________| |
 |_______________|  |______________|
           | |              | |
           | |              | |
          _|_|______________|_|__
         |                       |
         |      MAIN MEMORY      |
         |_______________________|


  Time     Command                 CPU 1 (Cache)      CPU 2 (Cache)        Main Memory
-------  ----------              ----------------    --------------       -------------
  1          ---                       ---                ---                x = 10
  2       Read x  (on cpu1)           x = 10              ---                x = 10
  3       Write x <--20 (on cpu1)     x = 20              ---                x = 10
  4       Read  x (on cpu2)           x = 20              x = 10             x = 10
  5       put cache to Main mem       x = 20              x = 10             x = 20

For example, Above execution order, x value is wrong on CPU2. x value already changed by CPU1.If x variable is defined as volatile, all write operation reflect to main memory instantly.

这篇关于线程缓存和Java内存模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 01:15