Java happen before(JSR133)_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java happen before(JSR133)

Java happen before(JSR133)

 2013/9/23 0:26:42  城的灯  程序员俱乐部  我要评论(0)
  • 摘要:相信对Java并发编程有所了解的人一定知道JMM,Java内存模型主要就是用来控制线程之间通信的,JMM决定了一个线程对共享变量的修改何时对别的线程可见。JMM定义了线程和主内存之间的抽象关系:线程之间的共享变量存储在主内存(mainmemory)中,每个线程都有一个私有的本地内存(localmemory),本地内存中存储了该线程以读/写共享变量的副本。本地内存是JMM的一个抽象概念,并不真实存在。从jdk5开始JSR133提出了新的内存模式即happenbefore的概念
  • 标签:for Java JSR APP JS
相信对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中成功返回。
上一篇: Java Serialization 下一篇: 没有下一篇了!
发表评论
用户名: 匿名