About your code
In your code, the for-each loop repeats through the list, and your osEvent modifies the list. Two threads working simultaneously can try: iterate over the list, and the other - add elements to it. Your for loop creates an iterator.
You can do the following (assuming these are only two places where this happens):
//osEvent synchronized(this.list) { list.add( new Particle( message.x, message.y ) ); } //draw synchronized(this.list) { for( Particle p : list ) { p.draw(); if( p.isComplete ) { completedParticles.add( p ); } } }
Or, as I explain below, make a copy of the vector before repeating it, which is likely to be better.
About the exception of parallel modification
This exception is not necessarily thrown in multi-threaded code. This happens when you modify a collection while it is repeating. You can get this exception even in single-threaded applications. For example, in a for-each loop, if you delete or add items to the list, you get a ConcurrentModificationException .
Thus, adding synchronization to the code will not necessarily solve the problem. Some alternatives are to copy duplicate data or use iterators that accept the changes (like ListIterator) or a collection of snapshot iterators.
Obviously, in the multi-threaded part of the code, you still have to take care of synchronization to avoid further problems.
Let me give you a few examples:
Suppose you want to remove items from a collection, iterate over it. Your alternatives to avoid ConcurrentModificationException :
List<Book> books = new ArrayList<Book>(); books.add(new Book(new ISBN("0-201-63361-2"))); books.add(new Book(new ISBN("0-201-63361-3"))); books.add(new Book(new ISBN("0-201-63361-4")));
Collect all the records that you want to delete in the extended loop, and after the iteration is completed, you will delete all the records found.
ISBN isbn = new ISBN("0-201-63361-2"); List<Book> found = new ArrayList<Book>(); for(Book book : books){ if(book.getIsbn().equals(isbn)){ found.add(book); } } books.removeAll(found);
Or you can use ListIterator , which supports the 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 multi-threaded environment, you might consider creating a copy of the collection before iterating, allowing others to modify the original collection without affecting the iteration:
synchronized(this.books) { List<Book> copyOfBooks = new ArrayList<Book>(this.books) } for(Book book : copyOfBooks) { System.out.println(book); }
Alternatively, you can use other types of collections using snapshot iterators such as java.util.ConcurrentCopyOnWriteArrayList , which guarantees not to throw a ConcurrentModificationException . But read the documentation first, because this type of collection is not suitable for all scenarios.