2 Replies Latest reply: Dec 9, 2012 11:51 AM by jtahlborn RSS

    synchronized ConcurrentModificationException

      I've written the following test code to experiment with concurrent programming. From what I can tell, everything is synchronized properly, yet I'm still receiving a ConcurrentModificationException. Have I made any obvious errors?

      Consider the following 3 classes:
      1) SynchronizationManager: mediates access to the list of Synchronizable objects
      2) Synchronizable: has a synchronize() method
      3) Test: creates a SynchronizationManager, starts it, then intermittently adds/removes Synchronizable objects to the list using only register() and unregister()
      import java.util.ArrayList;
      import java.util.List;
      public class SynchronizationManager {
          private List<Synchronizable> syncs = new ArrayList<Synchronizable>();
          public SynchronizationManager() {}
          public synchronized void start() {
              new Thread() {
                  public void run() {
                      while (true) {
                          try {
                          catch (Exception e) {}
          public synchronized void register(Synchronizable sync) {
          public synchronized void unregister(Synchronizable sync) {
          public synchronized void synchronize() {
              for (Synchronizable sync : syncs)
        • 1. Re: synchronized ConcurrentModificationException
          In your synchronized the method calls but not the List.

          So, while iterating List in
          for (String sync : syncs){}

          it will throw java.util.ConcurrentModificationException

          Use below method to synchronize List

          synchronized(arrayList) {
          Iterator it=arrayList.iterator();
          while(it.hasNext()) {

          Edited by: nitul.kukadia on Dec 9, 2012 6:23 AM
          • 2. Re: synchronized ConcurrentModificationException
            despite its name, ConcurrentModificationException really has nothing to do with threading. while it can be caused by multiple threads, most often it is caused by just a single thread. your code is correctly synchronized.

            you haven't shown all your code, but my guess is that one of Synchronizable.syncronize() methods calls register/unregister, thus modifying the syncs list while it is being iterated (and since the same thread is iterating and modifying the list, your synchronization does not solve the problem). if you need to allow this behavior, use a list which allows modification during iteration, such as CopyOnWriteArrayList.