Java中 Happen-before 规则总结

来源:互联网 发布:2016大数据概念股龙头 编辑:程序博客网 时间:2024/06/04 19:32

详细见:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html

比较重要的几条

1)Actions prior to "releasing" synchronizer methods such as Lock.unlock,Semaphore.release, andCountDownLatch.countDown happen-before actions subsequent to a successful "acquiring" method such asLock.lock,Semaphore.acquire, Condition.await, andCountDownLatch.await on the same synchronizer object in another thread

2)  A write to a volatile field happens-before every subsequent read of that same field. Writes and reads ofvolatile fields have similar memory consistency effects as entering and exiting monitors, but donot entail mutual exclusion locking. 

3)  Actions in a thread prior to placing an object into any concurrent collectionhappen-before actions subsequent to the access or removal of that element from the collection in another thread. 


volatile变量和concurrent容器不仅是关于它们自身内容的,还可以用来当同步器,影响别的变量。

线程1线程2p1:a = 1p2:list.set(1,"t")// volatileFlag = truep3:list.get(2) // if(volatile_flag == true)p4:int b = a;
p2 和 p3处分别用一个volatile变量写(或concurrent容器的写)和volatile变量读(或concurrent容器读),就可以确保,如果是上图的执行轨迹,b是可以读到a的新值的。如果p2,p3出用普通容器或着非volatile变量,则即使p2先于p3执行,b也不一定得到a的新值。
concurrent包中的容器,一般put,add是进行了lock的,而get一般没有,为了保证规则3),一般会在put方法的最后写一个volatile变量,而在get方法的开始读取这个volatile变量,如下图的 put的2) 和get的3)。


0 0
原创粉丝点击