關于JMM(Java Memory Model)

What is a memory model?

At the processor level, a memory model defines necessary and sufficient conditions for knowing that writes to memory by other processors are visible to the current processor, and writes by the current processor are visible to other processors.

What is the JMM?

The Java Memory Model describes what behaviors are legal in multithreaded code, and how threads may interact through memory. 
It describes the relationship between variables in a program and the low-level details of storing and retrieving them to and from memory or registers in a real computer system. 
It does this in a way that can be implemented correctly using a wide variety of hardware and a wide variety of compiler optimizations.

What does synchronization do?

  • mutual exclusion -- only one thread can hold a monitor at once
  • ensures that memory writes by a thread before or during a synchronized block are made visible in a predictable manner to other threads which synchronize on the same monitor.

Happen before

When one action happens before another, the first is guaranteed to be ordered before and visible to the second

The rules of this ordering are as follows:

  • Each action in a thread happens before every action in that thread that comes later in the program's order.
  • An unlock on a monitor happens before every subsequent lock on that same monitor.
  • A write to a volatile field happens before every subsequent read of that same volatile.
  • A call to start() on a thread happens before any actions in the started thread.
  • All actions in a thread happen before any other thread successfully returns from a join() on that thread.

What does volatile do?

  • ensure that after fields are written, they are flushed out of the cache to main memory
  • before a volatile field is read, the cache must be invalidated so that the value in main memory, not the local processor cache, is the one seen.
    下面是一個volatile的用法
class VolatileExample {
      int x = 0;
      volatile boolean v = false;
      public void writer() {
        x = 42;
        v = true;
      }

      public void reader() {
        if (v == true) {
          //uses x - guaranteed to see 42.
        }
    }
}

也許有人會問,x并沒有volatitle修飾,為什么也保證了可見性?解釋如下:

The write to v in writer releases the write to x to memory, and the read of v acquires that value from memory. 
Volatile or not, anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f.

小弟在上一篇文章中提到過,volatile相當于在指令前添加了LOCK指令(內存屏障),即:

  • 內存中在寫volatile后插入了write-barrier,release工作內存中數據到主存;
  • 讀volatile之前插入了read-barrier,將主存數據刷新到工作內存。

引用

淺析java內存模型--JMM(Java Memory Model)
JSR 133 (Java Memory Model) FAQ
深入理解Java內存模型(一)——基礎

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容