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内存模型(一)——基础