ConcurrentModificationException in List

In the following code I am getting a ConcurrentModificationException that I can't seem to rectify.
I have tried
1. sync'ing the 2 public methods
2. sync'ing within the methods (currently shown in code) this was most often recommended in forums that I have read on this problem.
3. sync'ing on the current object ("this", as shown in the code) and sync'ing on the list object itself.
4. Using Collections.synchronizedList(new Vector ...)
After chasing the problem I am pretty sure that the .add method is being called while the Iteraor loop is running, but shouldn't sync'ing fix that? The list is private and is not accessed from any other class outside the current one shown. Is there something wrong with my sync'ing?
Any recommendations will be appreciated.
Thanks,
sseric
Error:
Exception in thread "Thread-2" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
at java.util.AbstractList$Itr.next(AbstractList.java:420)
at genetviz.utils.BroadcastGraphAction.broadcast(BroadcastGraphAction.java:80)
at genetviz.utils.Graph.init(Graph.java:106)
at genetviz.io.FileOpener$FileLoader.run(FileOpener.java:312)
at java.lang.Thread.run(Thread.java:595)
Code:
import java.util.*;
import javax.swing.event.ChangeEvent;
import java.awt.Component;
import java.awt.Dimension;
public abstract class BroadcastGraphAction extends GraphRenderer
     implements GraphListener {
public abstract void setGraph(Graph graph);
private Vector<GraphListener> graphListenerList = new Vector<GraphListener>();
public void addGraphListener(GraphListener gl)
synchronized(this)
graphListenerList.add(gl);
public void broadcast(Graph gr)
if(gr == null) return;
synchronized(this)
for (Iterator iter = graphListenerList.iterator(); iter.hasNext();)
Object obj = iter.next();
if (obj instanceof GraphListener) ((GraphListener)obj).setGraph(gr);
}

takeshi10,
please see below for response,
when posting code, remember to use code tags...thank you. I'm new to the forums
except operations with the iterator, you shouldnt add / remove items on the list while iterating over it...yep, that's the problem.
i believe the setGraph method is adding the Graph to the list (tough, because of its abstractness i cant really tell)...no. the "Graph" is independent of the "GraphListener" and is not being added to the graphListenerList. The problem appears to be that .add is being called after .iterator is called on the graphListenerList. This is what I need to prevent through synchronization, or other techniques.
sync'inc will only prevent acess by other threads... right, which is why I used it in my code. So one of 2 things is happening then,
1. my synchronization is correct and it is not another thread causing the exception
2. Something is wrong with my synchronization
Though I'm not familiar with this, I tried something on the first note. I created a thread in the current class keeping it alive with a while loop and Thread.sleep, and I tried locking on it to ensure that an independent thread controlled the locking, for example,
public void addGraphListener(GraphListener gl)
     if(lock==null)
     { lock = new Thread(new LockRunner());}
     synchronized(lock)
        graphListenerList.add(gl);
  private class LockRunner extends Object implements Runnable
     public void run()
        try {
          while(true) Thread.sleep(1000);
           } catch (InterruptedException e) {
            System.out.println("BroadcastGraphAction sleep exception");
public void broadcast(Graph gr)
     if(gr == null) return;
     if(lock==null)
       lock = new Thread(new LockRunner());
     synchronized(lock)
       for (Iterator iter = graphListenerList.iterator(); iter.hasNext();)
           Object obj = iter.next();
           if (obj instanceof GraphListener) ((GraphListener)obj).setGraph(gr);
  }This did not work either. Unfortunately, I am only marginally experienced with threads and thread locking so I'm not quite sure I'm getting this right (well, obvioudly I'm not getting this right). Other suggestions?
sseric

Similar Messages

  • I have problem ConcurrentModificationException

    [java] Exception in thread "Play" java.util.ConcurrentModificationException
      public List<InventoryItem> getDeathDroppedItems(boolean isSkulled) {
            List<InventoryItem> deathDrop = new ArrayList<InventoryItem>();
            if(isSkulled) {
                deathDrop.addAll(getInventoryItems());
                getInventoryItems().clear();
            } else {
                for(InventoryItem i : getInventoryItems()) {
                    if(i.isStackable()) {
                        deathDrop.add(i);
                        remove(i);
                if(getInventorySize() > 3) {
                    HashMap<Integer, InventoryItem> priceSortedItems = new HashMap<Integer, InventoryItem>();
                    for(InventoryItem i : getInventoryItems())
                        priceSortedItems.put(i.getDefaultPrice(), i);
                    // Hack to sort the collection according to price
                    List<Map.Entry<Integer, InventoryItem>> itemEntries =
                            new ArrayList<Map.Entry<Integer, InventoryItem>>(priceSortedItems.entrySet());
                    Collections.sort(itemEntries,
                        new Comparator<Map.Entry<Integer, InventoryItem>>() {
                            public int compare(Map.Entry<Integer, InventoryItem> i, Map.Entry<Integer, InventoryItem> j) {
                                return (i.getKey().equals(j.getKey()) ? 0 : (i.getKey() > j.getKey() ? 1 : -1));
                    do {
                        Map.Entry<Integer, InventoryItem> i = itemEntries.get(0);
                        remove(i.getValue());
                        deathDrop.add(i.getValue());
                        itemEntries.remove(i);
                    } while(itemEntries.size() > 3);
            return deathDrop;
        }can someone tell me what give this exception ? thanks.. i am confused
    null

    Here we go it happened.
    [java] Exception in thread "play" java.util.ConcurrentModification
    Exception
    [java] at java.util.AbstractList$Itr.checkForComodification(AbstractLis
    t.java:372)
    [java] at java.util.AbstractList$Itr.next(AbstractList.java:343)
    [java] at blah.blah.getDeathDroppedItems(Inventory.java:315)
    315... which is line 8
    " for(InventoryItem i : getInventoryItems()) { "
    nevermind I don't need help ill solve this.
    null

  • Change a collection while you're iterating...

    I read from somewhere that changing a Collection while you're iterating with an Iterator would risk a ConcurrentModificationException, but the source didn't include an example code to show this so I don't fully understand it. Could anyone give an example code when this would happen? Thanks

    Don't use this code! This is an example how you'll get a ConcurrentModificationException.
    List<String> l = new ArrayList<String>();
    l.add("foo");
    l.add("bar");
    l.add("foobar");
    for (String s : l) {
      System.out.println(s);
      l.remove("bar");
    }

  • Iterator List Error "java.util.ConcurrentModificationException"

    Hi,
    I'm with a problem. I've got a set of objects in a List. I'm iterating the list and during this process, I have to add more objects to the list. The system returns the exception "java.util.ConcurrentModificationException".
    What is the solution to this problem, that is, how can I iterate a list, adding or removig elements without error
    Thanx
    MP

    You cannot add to a list while iterators are in progress. You can remove elements by calling the remove method on the iterator.
    If you need to both iterate and add, consider iterating a copy of the list, like so:
    List copy = new ArrayList(originalList);
    for (Iterator it = copy.iterator(); it.hasNext(); ) {
       // call originalList.add here
    }You could also consider indexing into the list (if it's an ArrayList), and then "bumping" your indices as you add elements.

  • Clear list

    how can i clear list compleatly
    there are 2 methos remove and removeAll but remove all ask fo collection as parameter
    let say i have list of strings
    ArrayList<String> myList = new ArrayList<String>()
    myList.removeAll(/*????*/); or may be ther is better way to clear the list compleatly ??
    what i did i creat for loop and remove elment by element but at the end i get this error
    Exception in thread "main" java.util.ConcurrentModificationException
         at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
         at java.util.AbstractList$Itr.next(Unknown Source)
         at model.Client.clearPasket(Client.java:99)
         at inputAndOutput.ProductInput.confirmDeleting(ProductInput.java:92)
         at inputAndOutput.ProductInput.statusAction(ProductInput.java:65)
         at View.OrderAssistance.showallcategories(OrderAssistance.java:87)
         at View.OnlineOrder.main(OnlineOrder.java:13)

    If there's nothing else that has a reference to that list, you're probably better off just creating a new one. It's not likely to make a big difference, but it can give slightly better GC performance.

  • List with multiple Iterators - result predictible?

    Hi,
    I have a situation where a list is used by two Iterators:
    List a;
    Iterator i1 = a.iterator();
    while (i1.hasNext()) {
    Object o1 = i1.next();
    Iterator i2 = a.iterator();
    while (i2.hasNext()) {
    Object o2 = i2.next();
    // do something to "o2" - modify or remove through i2.remove()
    I have seen other discussions, but my impression is it's mostly "Hash" or "Tree" that has a un-predictible result, or even clearer - fast-failing. For a List, it seems to me what would happen is quite certain (e.g. if the inner iterator removes an object, that object would be gone from the collection, but the outer iterator would still hold a reference to it, thus still be able to access it). However, in Java API, Iterator.remove() method has notes saying it's "unspecified" for all modifications unless using that particular method correctly.
    I think this is designed on purpose, but don't know why. Any thoughts?
    Thanks,

    An Iterator.delete() has the spec:
    public void remove()
    Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
    So when in your example the second iterator modifies the underlying collection it breaks the first instance iterator behavior which has then an unpredictable result.
    Using a List.iterator() seems to change nothing :
    public Iterator iterator()
    Returns an iterator over the elements in this list in proper sequence.
    Specified by:
    iterator in interface Collection
    Returns:
    an iterator over the elements in this list in proper sequence.
    So you code isn't garanty to run as you quote it running. The i2 is safe not i1 if you use i2.remove().
    I did this test:
         List v1 = new Vector();
         v1.add("1");
         v1.add("2");
         v1.add("3");
         Iterator i1 = v1.iterator();
         while (i1.hasNext()) {
              Object o1 = i1.next(); // At second iteration I got a ConcurrentModificationException here.
              Iterator i2 = v1.iterator();
              while (i2.hasNext()) {
                   i2.next();
                   i2.remove();
              System.out.println(o1);
    That's a typical unexpected results because hasNext() answered true but next() failed.
    Now if your question is why this spec, I dunno, I could only guess that the purpose of Iterator generic interface is to allow to have efficient implementation at price of non concurent modification access.

  • Concurrent modification exception while iterating through list

    Hi,
    I have a list of objects. I use for each loop in java to iterate through that list of objects and display them.
    The problem is that while iterating other thread can add or remove some objects from that list, and I get ConcurrentModificationException.
    How can I handle this problem. How can I be sure that I am iteration through the updated list.
    Thank you

    Synchonize on the list before iterating through it, and make sure that other code also synchronizes on the list before adding to it or removing from it. Using a list implementation that simply synchronizes all the methods (e.g. Vector) will not do that, you have to do it yourself.

  • ConcurrentModificationException in drawing code

    Hi all,
    I'm getting a ConcurrentModificationException and I'm having a bit of a hard time figuring out how to prevent it - I can't even really understand why it happens yet.
    I'm running a simulation of moving bodies in some world, and am using a Swing Timer to fire drawing events. The events fired by the timer are handled by a class WorldView, which draws the world and in turn uses BodyView objects to draw the bodies in the world. The exception occurs in the following code:
    public class SimAgentBodyView extends AgentBodyView {
      @Override
      public void draw( Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.red);
        //cam is a simulated camera object mounted on the agent body               
        List<ISimBody> visBodies = cam.getVisibleObjects();
        for ( Body b : visBodies ) //Exception occurs in this loop
         g2d.draw(b.getFigure().getBounds2D());So apparently the visBodies list is being modified somewhere else while the drawing occurs. I don't really get this since I only use a single thread for the simulation which executes in the even-dispatching thread. The Timer runs in a separate thread but according to the API the event handler for the timer executes in the event-dispatching thread; i.e. both the simulation and the drawing mechanism are executing in the event-dispatching thread, so how can the simulation modify the list while the drawing happens?
    I'm rather short on time and the drawing is usually switched off to speed up the simulation anwyay, so even if it is not obvious what the problem is, is there a quick way to fix this? E.g. adding a synchronized block to the drawing code?
    Thanks
    Matt

    jverd wrote:
    CME is thrown on a best effort basis. There's no guarantee when it will be thrown, or even that it will be at all.I understand, thanks.
    Before you avoid the clear and simple solution for performance reasons, have you actually tested and found a performance problem with it?Good point, I haven't. But from profiling the app I know that during a standard run the list will be modified around 400 million times, and read (a loop through the entire list) about 200k - 800k times, depending on how long the run takes. From what I've read it seems that a concurrent collection will take significantly longer in this case. But you're right, maybe I should just try.
    I only posted a tiny bit of the code because at the time I did think that was the relevant bit, since I was under the impression that there was just a single thread accessing the list. The complete code follows, although again I'll take out parts that do not involve the list to make it clearer.
    public class LineCamera implements PhysicalSensor {
         public List<ISimBody> getVisibleObjects() {
              return visibleObjects;
         @Override
         public double[] getReading() {
              List<Body> objectsInRange = world.getIntersectingObjects(visionArea);
              visibleObjects.clear(); //<--- List is cleared here
              calcImage(objectsInRange);
              return image;
            public void calcImage( List<Body> objects ) {
              Set<BodyDistance> sortedObjs = sortObjectsByDistance(objects);
              for ( Path2D.Double slice : slices ) {
                   for ( BodyDistance obj : sortedObjs ) {
                        if ( slice.intersects(obj.bounds) ) {
                             visibleObjects.add(obj.body); //<--- List is modified here
                                            ...The code that reads the list is just the code that I posted earlier. The quick and dirty solution that I adopted now is just to clone the list in the code that does the drawing. Since the drawing is mainly for testing and seeing what's going on, speed is not so important there. Plus this avoids having to synchronize the modifications on the list; since this code is always executed (even when drawing is switched off), speed is of the essence. However it's quite nasty of course so if you know of anything better please let me know. Thanks!

  • To get discret sublist from List

    Hi
    I need to get a sublist from List but it is not continuous list from the List.
    The method subList(int fromindex, int toindex) in List class returns a sublist with the specific range(from-to index).
    But how can it be made, such NOT continuous sublist that consists of index 0,1,2,5,6,8,10, ... of base List.

    A sublist is not a new list, but a certain view (think of it as a "window") of an existing list. So, when something in the original range changes, it changes in the sublist too.
    So, when you try to combine sublists of the same List, this will reflect on the original list and lead to your concurrentModificationException.
    The question is: is the sublist really what you want? Because the reason for sublists is to examine changes in a certain range, but what you want sounds more like a completely new composed list.
    I suggest you create a new List with exactly the items you want to have. For example:
    List myList = new ArrayList(someSublist);
    myList.add(someItem);
    myList.addAll(anotherList);
    // ...However, sorting changes in the original List will not reflect in the new List. For that, you might to write your own sublist, that points to the indices you'd like to watch instead of the objects.

  • ConcurrentModificationException when operating on an ArrayList

    Hi,
    I've got a strange problem. I'm working with a heavily multithreaded program. I have the following code:
    public abstract class GHAgentTaskThread implements Runnable, GenericObserverSubject {
    protected List observingResultDispatchers = new ArrayList();
    public final void addObserver(GenericObserverObserver subscriber) {
    synchronized (observingResultDispatchers) {
    observingResultDispatchers.add(subscriber);
    public final void removeObserver(GenericObserverObserver subscriber) {
    synchronized (observingResultDispatchers) {
    observingResultDispatchers.remove(subscriber);
    protected final void notifyObservingDispatchers() {
    synchronized (observingResultDispatchers) {
    Iterator i = observingResultDispatchers.iterator();
    GenericObserverObserver currentObserver;
    while (i.hasNext()) {
    currentObserver = (GenericObserverObserver) i.next(); //****
    currentObserver.notify(this);
    observersIterator = null;
    //Other stuff
    public class TokenryServerRequestTokenTask
    extends GHAgentTaskThread
    implements Runnable {
    public void run() {
    //do some stuff
    notifyObservingDispatchers();
    I have an external class which creates a new instance of the thread:
    GHAgentTaskThread myThread = new TokenryServerRequestTokenTask();
    It then adds itself as a listener:
    myThread.addObserver(this);
    This all works ok. I then start then thread and it goes and does the work I've specified. However, at the end of the run method when I try and notify the observers that the work is done with notifyObservingDispatchers(), I'm getting a:
    java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:444)
    at java.util.AbstractList$Itr.next(AbstractList.java:421)
    The line this is happeneing at is the :
    currentObserver = (GenericObserverObserver) i.next();
    line, which I've marked //**** in the code above.
    Why is this happening? I thought, that given I've synchronized all of the code that deals with the List (which is private) on the List itself that only one thing could be operating on it at one time, and hence this shouldn't occur. Strangely enough too, it doesn't seem to be affecting my program either - it works. However, exceptions are not thrown for no reason!
    If anyone can suggest how this could be sorted I'd be very grateful.
    Many thanks,
    Stu

    To englarge slightly on what _JN said, I speculate
    that when your GenericObserverObserver.notify() method
    is called, it calls one of your other methods in a way
    that modifies the list.
    cut
    Got it in one - I've just spotted that. I was attempting to remove the observer from the subject from within the GenericObserverObserver.notify() method... whoops!
    Cheers for the suggestion about the LinkedList - that's also a good idea.
    Thank you both for your help.
    Cheers,
    Stu

  • Getting ConcurrentModificationException

    Hi,
    I am getting this ConcurrentModificationException as shown by the following stack trace.
    java.util.ConcurrentModificationException
         at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:448)
         at java.util.AbstractList$Itr.next(AbstractList.java:419)
         at NLPMain.updateRoutingTableForDeadNode(NLPMain.java:94)
         at NLPMain.checkForDeadNodes(NLPMain.java:84)
         at NLPMain$RemindTask.run(NLPMain.java:64)
         at java.util.TimerThread.mainLoop(Timer.java:432)
         at java.util.TimerThread.run(Timer.java:382)
    I actually have a TimerTaskthread that is constantly sending routing updates... i.e. send its RouitngTable which is a vector....and in case a node goes down,,that node has to be removed from the routing table...at the same time some other thread might be looking up the routing table for forwarding packets.., etc.
    So logically the situation is multiple threads trying to access the routingTable (vector)..some modifyng it..other trying to Iterate over it. and this gives rise to this exception.
    I tried making use of synchronized keyword at a few places (but as I don't exactly know how to use synchronized) I cannot figure out. how to fix this...coz I'm still getting the same exception.

    There are 2 cases where this exception will raise
    1 ) There might be a case (bug in you code)
    while iteration you should remove object (if required) using iterator.remove()
    not list.remove(Object).
    2 )Well this is not a case of synchronisation, in multi threaded environment, there is a possibility of, 2 threads iterating on the object (Vector/ArrayList) simultanously.
    If you look into the source code of (java.util.AbstractList), this is the same case. When one thread is iterating, the other has modified (added/removed) elements from the list.
    So you should handle this exception and on encountering this
    -- You should skip the clean up, to happen it on next scheduled time or reiterate on the
    -- you should start new iteration in the catch block, if cleanup is that necessary.

  • Reposting: Question regarding iteration over synchronized list

    [added proper markup]
    I've got an A-Life program I work on for fun. I thought I understood (sorta) synchronized collections, but this puzzles me. The method body is as follows:
         * Create new animals from existing animals
         * @return The cohort of newborn animals
        public List<IAnimal> regenerate() {
            List<IAnimal> children = new ArrayList<IAnimal>();
            synchronized (animalList) {
                Iterator<IAnimal> it = animalList.iterator();          // must be in synchro block according to JDK notes
                 while (it.hasNext()) {
                     IAnimal a = it.next();
                     if (a.isPregnant() && ((GeneModel.getInstance().getTicks() % getEnvironment().getAnimal().getReproCycle()) == 0)) {
                         IAnimal child = a.reproduce();
                         children.add(child);                    // newborns
    //                     animalList.add(child);                    // the whole population  //THROWS CME!
                 animalList.addAll(children);                                     // does not throw CME
            return children;
        }Animal list is a synchronized list (backed by and ArrayList). Note that I've synchronized on the list, yet adding children individually throws a ConcurrentModificationException (I did overwrite the add() method on the backing list, but I wouldn't think that would be a problem; it might be in that it iterates over itself... but synchronizing that doesn't help, either).
    Anyhow, doing an addAll outside of the synchronization block works fine (also works if I loop through the children and add them at this point).
    Is it my override of the add() method? From what I can see, the synchronized wrapper just adds a mutex to each access method in the backing list. Here's the method override:
          List<IAnimal> backingList =
                new LinkedList<IAnimal>() {
                     * Checks that we're not putting one animal on top of another. If we are, we generate a new animal and
                     * try again.
                     * @param   animal  The animal to be added
                     * @return  true
                    public boolean add(IAnimal animal) {
                        boolean added = false;
    outer:
                        do {
                            // synchronized (this) {                // DIDN'T HELP
                            Iterator<IAnimal> iAnimals = iterator();
                            while (iAnimals.hasNext()) {
                                //FIXME: this algorithm assumes square animals
                                Point existingAnimalLocation = iAnimals.next().getLocation();
                                double distance = existingAnimalLocation.distance(animal.getLocation());
                                if (distance < animal.getSize().getWidth()) {
                                    animal = new Animal();
                                    continue outer;
                            //}  //end unhelpful synchro block
                            super.add(animal);
                            added = true;
                        while (!added);
                        return added;
                    } // end method add
                };

    Jefferino wrote:
    spoon_ wrote:
    By the way that Iterators in Java are designed, you are not allowed to modify a list as you iterate over it.
    Not true: Iterator.remove().
    Edited by: Jefferino on Mar 20, 2008 2:24 AMOh yeah, you can modify it using the iterator's methods; but not using any of the collection's methods, like add().

  • Question regarding iteration over synchronized list

    I've got an A-Life program I work on for fun. I thought I understood (sorta) synchronized collections, but this puzzles me. The method body is as follows:
    * Create new animals from existing animals
    * @return The cohort of newborn animals
    public List<IAnimal> regenerate() {
    List<IAnimal> children = new ArrayList<IAnimal>();
    synchronized (animalList) {
    Iterator<IAnimal> it = animalList.iterator();          // must be in synchro block according to JDK notes
         while (it.hasNext()) {
         IAnimal a = it.next();
         if (a.isPregnant() && ((GeneModel.getInstance().getTicks() % getEnvironment().getAnimal().getReproCycle()) == 0)) {
         IAnimal child = a.reproduce();
         children.add(child);                    // newborns
    //     animalList.add(child);                    // the whole population //THROWS CME!
         animalList.addAll(children); // does not throw CME
    return children;
    Animal list is a synchronized list (backed by and ArrayList). Note that I've synchronized on the list, yet adding children individually throws a ConcurrentModificationException (I did overwrite the add() method on the backing list, but I wouldn't think that would be a problem; it might be in that it iterates over itself... but synchronizing that doesn't help, either).
    Anyhow, doing an addAll outside of the synchronization block works fine (also works if I loop through the children and add them at this point).
    Is it my override of the add() method? From what I can see, the synchronized wrapper just adds a mutex to each access method in the backing list. Here's the method override:
    List<IAnimal> backingList =
    new LinkedList<IAnimal>() {
    * Checks that we're not putting one animal on top of another. If we are, we generate a new animal and
    * try again.
    * @param animal The animal to be added
    * @return true
    public boolean add(IAnimal animal) {
    boolean added = false;
    outer:
    do {
    // synchronized (this) {                // DIDN'T HELP
    Iterator<IAnimal> iAnimals = iterator();
    while (iAnimals.hasNext()) {
    //FIXME: this algorithm assumes square animals
    Point existingAnimalLocation = iAnimals.next().getLocation();
    double distance = existingAnimalLocation.distance(animal.getLocation());
    if (distance < animal.getSize().getWidth()) {
    animal = new Animal();
    continue outer;
    //} //end unhelpful synchro block
    super.add(animal);
    added = true;
    while (!added);
    return added;
    } // end method add
    };

    Your code is not formatted (use code tags for this) but it seems to me that you add elements to the list while you iterate over it, hence a ConcurrentModificationException is thrown. Use a ListIterator if you want to add to the list while iterating.

  • Why do I get a ConcurrentModificationException?

    I am using a LinkedList to store objects.
    Allways when I remove the first object with
    list = removeFirst();I get the following error:
    Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
            at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:7
    61)
            at java.util.LinkedList$ListItr.next(LinkedList.java:696)
            at Veterinar$N�staLyss.actionPerformed(Program.java:163)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:19
    95)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.jav
    a:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6038)
    .....I have tried to catch both ConcurrentModificationException and NoSuchElementException, but none of these works.
    The object I want to remove is being removed though, but I don�t want that exception.
    Please help!

    If your code becomes more complex, this might be a case where you need to use the iterator explicitly:
    void f(List<Animal> menagerie) {
        for(Iterator<Animal> i = menagerie.iterator(); i.hasNext(); ) {
            Animal pet = i.next();
            if (pet.isDead()) {
                i.remove();
                System.out.println("removed " + pet);
    }

  • Exception when retreiveing list from JNDI when the list updates at the same time.

    Hi
    I get a Exception when i am retreiving a list from the jndi:
    Start server side stack trace:
    com.sun.java.util.collections.ConcurrentModificationException
    at java.lang.Throwable.fillInStackTrace(Native Method)
    at java.lang.Throwable.fillInStackTrace(Compiled Code)
    at java.lang.Throwable.<init>(Compiled Code)
    at java.lang.Exception.<init>(Compiled Code)
    at java.lang.RuntimeException.<init>(Compiled Code)
    at
    com.sun.java.util.collections.ConcurrentModificationException.<init>(Concurr
    entModificationException.java:48)
    at com.sun.java.util.collections.HashMap$HashIterator.next(Compiled
    Code)
    at
    weblogic.jndi.toolkit.ReadOnlyMapBasedNamingStore$1.nextElement(Compiled
    Code)
    at weblogic.jndi.toolkit.AbstractNamingEnumeration.next(Compiled
    Code)
    at
    weblogic.jndi.toolkit.AbstractNamingEnumeration.nextElement(Compiled Code)
    at
    weblogic.utils.enumerations.BatchingEnumerationBase.nextBatch(Compiled Code)
    at
    weblogic.utils.enumerations.BatchingEnumerationBase_WLSkel.invoke(BatchingEn
    umerationBase_WLSkel.java:66)
    at weblogic.rmi.extensions.BasicServerObjectAdapter.invoke(Compiled
    Code)
    at
    weblogic.rmi.extensions.BasicRequestHandler.handleRequest(Compiled Code)
    at
    weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:1
    5)
    at weblogic.kernel.ExecuteThread.run(Compiled Code)
    End server side stack trace
    It says in the documentation of the weblogic server that: if the jndi is
    updated while you are retreiving the list from the server, you will only get
    the old list.
    And that is ok for me. But insted i get this exception that interupts the
    list retreiving. And if i just catch this exception an just continue or
    start again, it comes over and over.
    the code that does this, is like this:
    InitialContext context = new InitialContext(env);
    NamingEnumeration list = context.listBindings("sid");
    Vector copy = new Vector(10000,1000);
    log("Initiating copy of JNDI list!");
    try
    while (list.hasMore())
    copy.addElement(list.next());
    catch (Exception e)
    log("Copying interupted:" + e.toString());
    How can i solve this ?
    Is it a configuration of the server problem ?
    Are ther other ways of retreiving the list ?
    -Ståle Tomten

    Be carefull - you read Object two times, so if you
    have only one object you will get null after second
    reading, and NullPointerException as a result if you
    try to do smth with null.
    Wrong:
    while( inputFromServlet1.readObject() != null)
    Object o = inputFromServlet1.readObject();Previous man example is also wrong because you
    cannot declare anything in while
    Sorry for this one... I certainly must have spent too much time on these fora ;-)
    Thanks for the correction, by the way...
    Correct:
    Object o;
    while( (o = inputFromServlet1.readObject()) != null)
    String str = (String)o;
    System.out.println("Got Object");

Maybe you are looking for