线程缓存和 Java 内存模型 [英] Thread Caching and Java Memory model

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

问题描述

我正在尝试了解 Java 内存模型和线程.据我了解,每个线程都有一个主"线程的本地副本.记忆.因此,如果一个线程尝试更改某个对象的 int 变量,它会缓存 int 变量,如果它更改它,其他线程可能看不到更改.

I'm trying to understand the Java memory model and threads. As far as 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.

但是如果线程缓存某个对象而不是 int 呢?在这种情况下,哪些线程缓存了它?如果一个线程缓存了一个对象的引用,该对象状态的任何变化对其他线程都是不可见的吗?为什么?

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?

推荐答案

CPU 有不同级别的缓存 L1、L2、L3.每个 CPU(以及/可能 CPU 核心)都有自己的缓存.此缓存存储最小的主内存 (RAM) 集以提高性能.

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

例如,上面的执行顺序,在CPU2上x值是错误的.CPU1 已更改 x 值.如果将 x 变量定义为 volatile,则所有写操作都会立即反映到主内存中.

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 内存模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆