   [java] Thread problem: "java.util.ConcurrentModificationException"
  Hello folks!I have an ArrayList, arr.To this arraylist, I add/remove items (by pressing Enter/Esc).In my thread, I loop through this arraylist and print out all theelements.But if I add/remove one item exactly while the thread is readingfrom the arraylist, I get the ConcurrentModificationException.How do I solve this?I think I should use "synchronized" somehow?I don't get it to work...Anyone?Kind Regards   
  Wherever you are accessing the ArrayList do this (where theList is your ArrayList):...synchronized( theList ){    //loop through the list}......synchronized( theList ){    //Add an element to the list}...etc.That way, only one section of code will be allowed to use the ArrayList at a time.If responsiveness for adding and removing items is a priority, then you will have to clone the list in a sychronized block.  After you have cloned the list, release the lock and print it out so adding & removing can continue elsewhere.Cheers,Brett   ;  If I'm not mistaken, you can also create a synchronized List using a Collections' class method, synchronizedList().   ;  You should look into and understand the need for the java.util.concurrent package.Lizard   ;  Thanks dudes!I'll take a look at these three answers...   ;  Basically you can not add/remove when you are iterating over a collection that is not synchronized such as the ArrayList.;  You can use an Iterator instance to do the removal:Iterator it = list.iterator();while ( it.hasNext() ) {  it.remove();};  and with a ListIterator you can add...   ;Quote:Original post by Son of CainYou can use an Iterator instance to do the removal:Iterator it = list.iterator();while ( it.hasNext() ) {  it.remove();}But what happens if I try to "it.remove()" while my thread is reading the arraylist?   ;  You'll want to put a synchronized block around your iteration loop. E.g. synchronized (list){  for (Iterator it = list.iterator(); it.hasNext();)  {    it.remove();  }}because modifying the list from another thread will invalidate the iterator.   