Java中 Happen-before 规则总结

12 篇文章 0 订阅
11 篇文章 0 订阅

详细见: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, and CountDownLatch.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							线程2
	p1:a = 1			
	p2:list.set(1,"t")// volatileFlag = true		
							p3: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值