This discussion is archived
2 Replies Latest reply: Dec 9, 2012 9:51 AM by jtahlborn RSS

synchronized ConcurrentModificationException

910971 Newbie
Currently Being Moderated
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) {
                    synchronize();
                    try {
                        sleep(10);
                    }
                    catch (Exception e) {}
                }
            }
        }.start();
    }

    public synchronized void register(Synchronizable sync) {
        syncs.add(sync);
    }

    public synchronized void unregister(Synchronizable sync) {
        syncs.remove(sync);
    }

    public synchronized void synchronize() {
        for (Synchronizable sync : syncs)
            sync.synchronize();
    }
}
  • 1. Re: synchronized ConcurrentModificationException
    nitul.kukadia Newbie
    Currently Being Moderated
    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()) {
    System.out.println(it.next());
    }
    }

    Edited by: nitul.kukadia on Dec 9, 2012 6:23 AM
  • 2. Re: synchronized ConcurrentModificationException
    jtahlborn Expert
    Currently Being Moderated
    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.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points