相信对
Java并发编程有所了解的人一定知道JMM,Java
内存模型主要就是用来控制
线程之间通信的,JMM决定了一个线程对共享变量的修改何时对别的线程可见。JMM定义了线程和主内存之间的抽象关系:线程之间的共享变量存储在主内存(main memory)中,每个线程都有一个私有的本地内存(local memory),本地内存中存储了该线程以读/写共享变量的副本。本地内存是JMM的一个抽象概念,并不真实存在。
从jdk5开始
JSR133提出了新的内存模式即happen before的概念,通过找个概念阐述了多个操作的可见性。此处所说的是多个操作,而非多个线程,因为编译器重排序规则和
处理器重排序,并非按照我们写的代码的顺序执行。那什么是happen before呢?最简单的就是一个操作的结果对另一个可见,可以简单粗暴的
理解为什么在什么之间执行(实际上其实不是这样的)。
JSR133的目标:
Preserving existing safety guarantees, like type-safety, and strengthening others. For example, variable values may not be
created "out of thin air": each value for a variable observed by some
thread must be a value that
can reasonably be placed there by some thread.
The semantics of correctly synchronized programs should be as simple and intuitive as possible.
The semantics of incompletely or incorrectly synchronized programs should be defined so that potential security hazards are minimized.
Programmers should be able to reason confidently about how multithreaded programs interact with memory.
It should be possible to design correct, high performance
JVM implementations across a wide range of popular hardware architectures.
A new guarantee of initialization safety should be provided. If an object is properly constructed (which means that references to it do not escape during construction), then all threads which see a reference to that object will also see the values for its final fields that were set in the constructor, without the need for synchronization.
There should be minimal impact on existing code.
happen before规范:
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.
happen before翻译过来就是:
程序顺序规则:一个线程中的每个操作,happens- before 于该线程中的任意后续操作。
监视器锁规则:对一个监视器锁的
解锁,happens- before 于随后对这个监视器锁的加锁。
volatile变量规则:对一个volatile域的写,happens- before 于任意后续对这个volatile域的读。
传递性:如果A happens- before B,且B happens- before C,那么A happens- before C。
Thread.start()的调用会happens-before于启动线程里面的动作。
Thread中的所有动作都happens-before于其他线程从Thread.join中成功返回。