About Concurrent Modification Exception

來源:互聯網
上載者:User

About Concurrent Modification Exception

This exception is not necessarily thrown in a multithreaded code. It happens when you modify a collection while it is being iterated. You can get this exception even in single-threaded applications. For instance, in a for-each loop, if
you remove or add elements to a list, you end up getting a ConcurrentModificationException.

As such, adding synchronization to the code will not necessarily solve the problem. Some alternatives consist in making a copy of the data to be iterated, or using iterators that accept modifications (i.e. ListIterator), or a collection
with snapshot iterators.

Evidently, in a multithreaded piece of code, you would still have to take care of synchronization to avoid further problems.

Let me give some examples:

Let's say you want to delete items from a collection while iterating over it. Your alternatives to avoid aConcurrentModificationException are:

List<Book> books=
newArrayList<Book>();books.add(newBook(new
ISBN("0-201-63361-2")));books.add(newBook(new
ISBN("0-201-63361-3")));books.add(newBook(new
ISBN("0-201-63361-4")));

Collect all the records that you want to delete within an enhanced for loop, and after you finish iterating, you remove all found records.

ISBN isbn
= new ISBN("0-201-63361-2");List<Book>
found = newArrayList<Book>();for(Book
book: books){if(book.getIsbn().equals(isbn)){
found.add(book);}}books.removeAll(found);

Or you may use a ListIterator which has support for a remove/add method during the iteration itself.

ListIterator<Book> iter= books.listIterator();while(iter.hasNext()){if(iter.next().getIsbn().equals(isbn)){
iter.remove();}}

In a multithreaded environment, you might consider making a copy of the collection before iterating, as such, allowing others to modify the original collection without affecting iteration:

synchronized(this.books){
List<Book> copyOfBooks=
newArrayList<Book>(this.books)}for(Book
book : copyOfBooks){
System.out.println(book);}

Alternatively, you may consider using other types of collections using snapshot iterators, likejava.util.ConcurrentCopyOnWriteArrayList which guarantees not to throwConcurrentModificationException. But read the
documentation first, because this type of collection is not suitable for all scenarios.

 

 

Thank you for your answer. I am in fact doing exactly what you recommend in your second code example where elements are being removed after iteration. It is possible that something is being added to the list while it is being iterated.
However, as far as I can tell it would only be happening as a result of a concurrent procedure. – jeremynealbrownJul
3 '12 at 23:06

 

@jeremynealbrown Then synchronization must be broken in your program somewhere. At some point, your collection is being modified while somewhere else is being iterated. Take into account that most collection iterators are backed
by the original collection and that for-each loops use iterators behind the scenes. – Edwin DalorzoJul
3 '12 at 23:12

1

 

Wrapping the iteration processes in synchronized blocks seems to have fixed it quite well. Not only did it fix the problem, I also learned some really useful tricks that I'm sure I'll use again. Thanks for all of you help.!!
– jeremynealbrownJul
3 '12 at 23:38

 

 

 

From:http://stackoverflow.com/questions/11320310/how-can-java-util-concurrentmodificationexception-be-avoided-when-using-osc

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.