Thread Caching and Java Memory model

前端 未结 4 1938
野的像风
野的像风 2020-11-29 02:21

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 a

4条回答
  •  星月不相逢
    2020-11-29 02:54

    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.

提交回复
热议问题