Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

avoid concurrent modification - iterating over a list thats being modified

807606Mar 15 2007 — edited Mar 15 2007
I have a GUI which, when a button is pressed, adds a MyObject to a List (in this case, an ArrayList). In my design, I only provide an Iterator<MyObject> to access the elements of the list publicly.

I have a separate thread in a non-gui class that needs to iterate over this list every X millseconds. The problem is, I'm calling iter.next() while the list is being modified and it's throwing a ConcurrentModificationException. I understand this, I'm just not sure how to avoid it.

The code looks something like this (I'm on a different computer). Basically, when the button's pressed, it tells the controller to add the object. The controller then calls the model's model.addMyObject() method. This is where the list is modified.
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        controller.addMyObject(new MyObject());
    }
});
Then this completely separate class runs in the background, iterating over the list constantly.
public void run() {
    while (true) {
        Iterator<MyObject> iter = model.iterator();
        while (iter.hasNext()) {
            MyObject obj = iter.next();
            // do something with the object
        }

        // sleep X millseconds
    }
}
I haven't found many synchronization examples that give best practices for this type of scenario. The way I was going to attempt to solve this is to have the add method wait() while the thread polling class is iterating over the list. When the thread polling class is finished iterating, it notifies the model class that it's done.

1) I'm not exactly sure how to do this.. I don't deal with synchronization stuff that often.

2) It seems odd that the Thread polling class should have to care about the whole synchronization issue. Shouldn't this soley be the responsibility of the class that contains the List<MyObject>?

3) Is there a good tutorial that deals with Lists over multiple threads (instead of simply synchronizing primitive data)?

Thanks!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 12 2007
Added on Mar 15 2007
3 comments
123 views