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.
下面是一個(gè)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.
}
}
}
也許有人會(huì)問(wèn)狮崩,x并沒(méi)有volatitle修飾辞居,為什么也保證了可見(jiàn)性堂湖?解釋如下:
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.
小弟在上一篇文章中提到過(guò)镐侯,volatile相當(dāng)于在指令前添加了LOCK指令(內(nèi)存屏障),即:
- 內(nèi)存中在寫(xiě)volatile后插入了write-barrier,release工作內(nèi)存中數(shù)據(jù)到主存抖誉;
- 讀volatile之前插入了read-barrier估脆,將主存數(shù)據(jù)刷新到工作內(nèi)存钦奋。
引用
淺析java內(nèi)存模型--JMM(Java Memory Model)
JSR 133 (Java Memory Model) FAQ
深入理解Java內(nèi)存模型(一)——基礎(chǔ)