I used synchronized list, and i still get Concurre

2019-02-08 07:15发布

This question already has an answer here:

I'm using Vector instead of ArrayList to make a list safe in multi-threaded enviroment. But I keep getting ConcurrentModificationException when I trying to add items to the Vector while iterating it. Why is that and how can I prevent it?

3条回答
Anthone
2楼-- · 2019-02-08 07:27

If you need to iterate and add concurrently to your list, you should use a concurrent list, such as CopyOnWriteArrayList. Note that if you write a lot to the list it will not be very efficient.

Otherwise, if you use a Vector or a synchronizedList, you need to hold the list's lock while iterating. That will prevent the exception but it will also prevent concurrency...

查看更多
冷血范
3楼-- · 2019-02-08 07:39

You cannot modify a Vector while iterating over it. Store the items to add in a separate vector, and move them to the Vector when the loop is finished or loop over a copy of the original Vector.

ADDED: To get a mutex around the Vector in java, do this in both functions:

synchronized (list) {
  // modifying list
}

and:

synchronized (list) {
  // iterating over list
}

Of course I've assumed that the list is named list

查看更多
女痞
4楼-- · 2019-02-08 07:40

if you want to add items as you iterate, you'll want to use a ListIterator. by using Vector, you're not bypassing this rule (obviously), so I would recommend using the ArrayList instead.

查看更多
登录 后发表回答