java 并发容器


arraylist和linkedlist 的 add(),remove(),iterator()在多线程访问下都需要加锁

vector容器的add() remove() 操作是thread-safe,但iterator不是thread-safe,多线程使用下需要先锁

CopyOnWriteArrayList,容器的 add,remove,itertor都是thread-safe。 因为调用 iterator的时候, 会返回一个 snapshot,所以其他线程只会修改容器本身而不会改动snapshot. .

HashMap 不是threadsafe,  多线程下可使用 java.util.concurrent.ConcurrentHashMap 

关于copyonwriteArrayList的内部实现,可参考 https://www.cnblogs.com/dolphin0520/p/3938914.html


关于: Exception in thread "main" java.util.ConcurrentModificationException

List< Integer> list1 = new ArrayList< Integer>();
for ( int i = 0; i < 10; i++)
list1. add(i);

List< Integer> list2 = list1. subList( 0, 2);
List< Integer> list3 = list1. subList( 0, 4);
list2. clear();

System. out. println( list3. get( 0));

以上代码会报错:Exception in thread "main" java.util.ConcurrentModificationException

原因在于list3 是list1的view. 如果list1修改了,会导致它的view(也就是list3)无效

list2.clear()会导致list1的修改 (把list1的前两个element删掉),因为这是一个Structural modifications,导致它的所有view无效.

如果有疑惑,可查看 https://docs.oracle.com/javase/7/docs/api/java/util/List.html#subList(int,%20int)

上面写道:  sublist(fromIndex,toIndex ) Returns a view of the portion of this list between the specified from ndex, inclusive, and toIndex, exclusive. The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list. 

The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值