Collections.synchronizedList()不同锁造成的陷阱

今天看java并发编程时,发现一段有趣的代码。顺便记记笔记。

[java]  view plain  copy
 print ?
  1. @NotThreadSafe  
  2. class BadListHelper <E> {  
  3.     public List<E> list = Collections.synchronizedList(new ArrayList<E>());  
  4.   
  5.   
  6.     public synchronized boolean putIfAbsent(E x) {  
  7.         boolean absent = !list.contains(x);  
  8.         if (absent)  
  9.             list.add(x);  
  10.         return absent;  
  11.     }  
  12. }  

不仔细的看,还以为这个类是线程安全的,因为putIfAbsent方法加了synchronized。不过细心的同学就会发现原来putIfAbsent方法和List并不是使用的同一个锁对象,List使用的锁对象并不是BadListHelper,而是list。假如A线程进入putIfAbsent方法,list这个锁并没有被获取(A线程获取的是 BadListHelper这个对象),所以其他线程还能够获得list锁对象来改变list对象。boolean absent = !list.contains(x);当线程到这串代码结束时,其他线程获得list锁对象,从而就能调用list的方法来改变list对象,这时候就可能导致!list.contains(x)改变,即域absent并不是A线程得到的布尔类型。所以这个类并不是线程安全的。


 正确的代码

[java]  view plain  copy
 print ?
  1. @ThreadSafe  
  2. class GoodListHelper <E> {  
  3.     public List<E> list = Collections.synchronizedList(new ArrayList<E>());  
  4.   
  5.   
  6.     public boolean putIfAbsent(E x) {  
  7.         synchronized (list) {  //获得list锁对象,其他线程将不能获得list锁来来改变list对象。  
  8.             boolean absent = !list.contains(x);  
  9.             if (absent)  
  10.                 list.add(x);  
  11.             return absent;  
  12.         }  
  13.     }  
  14. }  

另外 :通过Collections.synchronizedList 获得的list,其自身具备的方法可以同步,其自身不具备的方法,需要手动同步,另外就是 iterator()方法也需要我们手动加上同步操作.
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值