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.

Similar Messages

  • Why am I still getting ConcurrentModificationException?!

    Here is a simple test that I ran on a collection that I have implemented, in which I try to add multiple objects to the collection in multiple threads. I have labelled the methods which modify the colleciton as synchronized, so I had thought it would not allow more than one LinkedCollection.add operation at a time. However, I am getting ConcurrentModificationExceptions from it. Below the test I have included the code for my LinkedCollection class and all other relevant classes, so that it's possible for anyone here to run it if needed. Thanks for any help!
    ==========================================================================================
    public class ThreadTest {
        public static void main(String[] args) {
            LinkedCollection<Integer> c = new LinkedCollection<Integer>();
            for (int i = 0; i < 10; i++) {
                Thread t = new Thread(new Berk(c, i * 10), "Thread " + i);
                t.start();
            System.out.println(c);
        static class Berk implements Runnable {
            private LinkedCollection<Integer> c;
            private int i;
            public Berk(LinkedCollection<Integer> c, int i) {
                this.c = c;
                this.i = i;
            public void run() {
                for (int i = 0; i < 10; i++)
                    c.add(this.i + i);
    }==========================================================================================
    import java.util.Collection;
    public class LinkedCollection<E> implements Collection<E>, PublicCloneable<LinkedCollection<E>>, ModificationEventGenerator {
        protected Position<E> head;
        protected int size;
        private LinkedCollection<ModificationListener> listeners;
        public LinkedCollection() {
            this(true);
        protected LinkedCollection(boolean notifyModifications) {
            listeners = notifyModifications ? new LinkedCollection<ModificationListener>(false) : null;
        public boolean isEmpty() {
            return head == null;
        public boolean contains(Object element) {
            return getFirstPosition(element) != null;
        public boolean containsAny(Collection<?> c) {
            for (Object element : c)
                if (contains(element))
                    return true;
            return false;
        public boolean containsAll(Collection<?> c) {
            for (Object element : c)
                if (!contains(element))
                    return false;
            return true;
        public int occurrences(Object element) {
            return getPositions(element).size();
        public int size() {
            return size;
        public synchronized boolean add(E element) {
            if (element != null) {
                generateModificationEvent();
                if (isEmpty())
                    head = new Position<E>(element);
                else
                    head.prev = head.prev.next = new Position<E>(element, head.prev, head);
                size++;
                return true;
            return false;
        public synchronized boolean addAll(Collection<? extends E> c) {
            boolean changed = false;
            for (E element : c)
                if (add(element))
                    changed = true;
            return changed;
        public synchronized boolean remove(Object element) {
            LinkedCollection<Position<E>> removals = getPositions(element);
            for (Position<E> current : removals) {
                if (size == 1)
                    head = null;
                else {
                    if (current == head)
                        head = head.next;
                    current.prev.next = current.next;
                    current.next.prev = current.prev;
                    current.prev = current.next = current;
                size--;
            return generateModificationEvent(!removals.isEmpty());
        public synchronized boolean removeAll(Collection<?> c) {
            boolean changed = false;
            for (Object element : c)
                if (remove(element))
                    changed = true;
            return changed;
        public synchronized boolean retainAll(Collection<?> c) {
            LinkedCollection<E> removals = new LinkedCollection<E>();
            for (E element : this)
                if (!c.contains(element))
                    removals.add(element);
            for (E element : removals)
                this.remove(element);
            return !removals.isEmpty();
        public synchronized void clear() {
            Position next;
            while (size > 0) {
                next = head.next;
                head.prev = head.next = head;
                head = next;
                size--;
            head = null;
            if (listeners != null)
                listeners.clear();
        public Object[] toArray() {
            Object[] array = new Object[size];
            int index = 0;
            for (E element : this)
                array[index++] = element;
            return array;       
        public <T> T[] toArray(T[] type) {
            T[] array = type.length < size ? (T[]) new Object[size] : type;
            int index = 0;
            for (E element : this)
                array[index++] = (T)element;
            if (array.length > size)
                array[index] = null;
            return array;
        public String toString() {
            String s = "";
            for (E element : this)
                s += element.toString() + " ";
            return s;
        public boolean equals(Object o) {
            if (!(o instanceof Collection<?>))
                return false;
            LinkedCollection<?> s = (LinkedCollection<?>)o;
            for (Object element : s)
                if (occurrences(element) != s.occurrences(element))
                    return false;
            for (E element : this)
                if (!s.contains(element))
                    return false;
            return true;
        public int hashCode() {
            return 0;
        public LinkedCollection<E> clone() {
            LinkedCollection<E> clone = new LinkedCollection<E>();
            clone.addAll(this);
            return clone;
        public void addModificationListener(ModificationListener m) {
            if (listeners != null && !listeners.contains(m))
                listeners.add(m);
        public void removeModificationListener(ModificationListener m) {
            if (listeners != null)
                listeners.remove(m);
        public void generateModificationEvent() {
            if (listeners != null)
                for (ModificationListener m : listeners)
                    m.modified(new ModificationEvent(this));
        public boolean generateModificationEvent(boolean condition) {
            if (condition)
                generateModificationEvent();
            return condition;
        public final java.util.Iterator<E> iterator() {
            return new Iterator<E>(this, head, head);
        protected LinkedCollection<Position<E>> getPositions(Object element) {
            LinkedCollection<Position<E>> matches = new LinkedCollection<Position<E>>(false);
            if (!isEmpty()) {
                Position<E> match = head.prev;
                int count = 0;
                while (matches.add(match.next == head && count++ > 0 ? null : (match = getFirstPosition(element, match.next))));
            return matches;
        protected Position<E> getFirstPosition(Object element, Position<E> start) {
            if (!isEmpty()) {
                Iterator i = new Iterator(this, start, head);
                while (i.hasNext())
                    if (i.next().equals(element)) {
                        i.terminate();
                        return i.currentPosition();
            return null;
        protected Position<E> getFirstPosition(Object element) {
            return getFirstPosition(element, head);
    }==========================================================================================
    import java.util.ConcurrentModificationException;
    import java.util.NoSuchElementException;
    class Iterator<E> implements java.util.Iterator<E>, ModificationListener {
        private ModificationEventGenerator parent;
        protected Position<E> start, end, current, next;
        private boolean started, hasNext, hasNextCalculated, terminatedExternally;
        public Iterator(ModificationEventGenerator parent, Position<E> start, Position<E> end) {
            this.parent = parent;
            parent.addModificationListener(this);
            this.start = start;
            this.end = end;
            current = null;
            next = start;
        public boolean hasNext() {
            checkTerminatedExternally();
            if (!hasNextCalculated) {
                hasNext = !(start == null || (started && (next == null || next == end)));
                hasNextCalculated = true;
            if (!hasNext)
                terminate();
            return hasNext;
        public E next() {
            return nextPosition().element();
        protected Position<E> nextPosition() {
            checkTerminatedExternally();
            if (!hasNext())
                throw new NoSuchElementException();
            started = true;
            hasNextCalculated = false;
            next = (current = next).next;
            return current;
        protected Position<E> currentPosition() {
            return current;
        public void remove() {
            throw new UnsupportedOperationException();
        public void modified(ModificationEvent e) throws ConcurrentModificationException {
            if (e.getSource() == parent)
                throw new ConcurrentModificationException();
        public void terminate() {
            terminate(true);
        private void terminate(boolean externally) {
            checkTerminatedExternally();
            parent.removeModificationListener(this);
            if (externally)
                terminatedExternally = true;
        private void checkTerminatedExternally() {
            if (terminatedExternally)
                throw new UnsupportedOperationException("It is not possible to use an iterator that has been terminated.");
    }==========================================================================================
    import java.util.Iterator;
    public class Position<E> {
        private E element;
        protected Position prev = this, next = this;
        public Position(E element) {
            this.element = element;
        public Position(E element, Position prev, Position next) {
            this(element);
            this.prev = prev;
            this.next = next;
        public E element() {
            return element;
        public String toString() {
            return "[" + prev.element.toString() + "]<[" + element.toString() + "]>[" + next.element.toString() + "] ";
    }==========================================================================================
    import java.util.EventListener;
    public interface ModificationListener extends EventListener {
        public void modified(ModificationEvent e);
    }==========================================================================================
    import java.util.EventObject;
    public class ModificationEvent extends EventObject {
        public ModificationEvent(Object source) {
            super(source);
    }==========================================================================================
    public interface ModificationEventGenerator {
        public void addModificationListener(ModificationListener m);
        public void removeModificationListener(ModificationListener m);
        public void generateModificationEvent();
    }==========================================================================================
    public interface PublicCloneable<T extends PublicCloneable<T>> {
        public T clone();
    }==========================================================================================

    I have changed my tests to call Collections.synchronizedCollection when initialising the collection, but now, although the exceptions no longer occur, hardly any of the elements are being added to the collection! Here is my new test code:
    import java.util.Collection;
    import java.util.Collections;
    public class GeneralTests {
        public static void main(String[] args) {
            Collection<Integer> c = Collections.synchronizedCollection(new LinkedCollection<Integer>());
            for (int i = 0; i < 10; i++) {
                Thread t = new Thread(new Berk(c, i * 10), "Thread " + i);
                t.start();
            System.out.println(c);
        static class Berk implements Runnable {
            private Collection<Integer> c;
            private int i;
            public Berk(Collection<Integer> c, int i) {
                this.c = c;
                this.i = i;
            public void run() {
                for (int i = 0; i < 10; i++)
                    c.add(this.i + i);
    }

  • Answer:  814 content management gets ConcurrentModificationException

    I wanted to get this into this news group for others to find.
    Solution: Open a ticket and get patch patch_CR211051_81SP4
    Problem:
    WLP 814 using content management P13N tags or APIs. While your portal is up and users have browsed content, run the portalAdmin--content update content, or use load_cm_data.sh and you get exception.
    FYI I believe this bug will most likely happen on SMP boxes. IE you'll not likely see this on a single CPU box. Just my guess based on experience.
    <Jan 21, 2005 3:55:13 PM EST> <Info> <EJB> <BEA-010051> <EJB Exception occurred during invocation from home: [email protected]51
    threw exception: java.util.ConcurrentModificationException
    java.util.ConcurrentModificationException
    at java.util.Hashtable$Enumerator.next()Ljava.lang.Object;(Unknown Source)
    at com.bea.p13n.cache.CacheImpl.createSet(Z)Ljava.util.Set;(CacheImpl.java:764)
    at com.bea.p13n.cache.CacheImpl.keySet()Ljava.util.Set;(CacheImpl.java:350)
    at com.bea.content.manager.internal.CacheHelper.flushAllBinaryCacheEntries(Ljava.lang.String;Ljava.lang.String;)V(CacheHelper.java:482)
    at com.bea.content.manager.internal.NodeOpsBean.updateProperties(Lcom.bea.content.ID;[Lcom.bea.content.Property;)Lcom.bea.content.Node;(NodeOpsBean.java:1391)
    at com.bea.content.manager.internal.NodeOpsEJB_e40s0j_ELOImpl.updateProperties(Lcom.bea.content.ID;[Lcom.bea.content.Property;)Lcom.bea.content.Node;(NodeOpsEJB_e40s0j_                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    iSync automatically takes the newest changes to data on your devices and applies them to all other devices when you sync.
    There is no manual override for similar content when syncing your phone. The ability to select data on one device or another appears on an initial sync when you choose to 'Merge' the data on the device and on the Mac. Doing this is often unsuccessful, so for an initial sync its better to start with a fully up-to-date Mac Address Book and a completely empty phone.
    Have you renamed the telephone number fields in the Mac Address Book? If you have, that can cause multiple phone numbers of the same type to appear. However Sony Ericsson phones only support one number of each type:
    work
    mobile
    home
    fax
    other
    If your fields in the Mac's Address Book are named anything other than this, set them back. Then make sure your Mac's Address Book is fully up-to-date, back it up, then click "Reset Sync History..." in iSync Preferences and re-sync your phone.
    .Mac Sync is separate to iSync and is for syncing Mac-to-Mac, so you can ignore any references to .Mac if you're just syncing your phone.
    For further iSync Tips see my web-site here:
    http://www.feisar.com/isync_tips.html

  • Looping through Collection and getting ConcurrentModificationException

    I'm trying to loop through a collection to delete some objects referenced by that collection but keep coming up against a ConcurrentModificationException.
    BwView view = svci.getViewsHandler().find("Lists");
                  Collection<BwSubscription> subarr = new TreeSet<BwSubscription>();
                  subarr = svci.getSubscriptionsHandler().getAll();  
                  if (subarr == null) {
                       logger.info("Its not working");
                  for (BwSubscription sub: subarr) {
                       logger.info("Removing subs " + sub);
                       svci.beginTransaction();
                       svci.getSubscriptionsHandler().delete(sub);
                       logger.info("Deleting calendars :" + sub);
                       svci.endTransaction();
                 The loop is allowing me to delete the first entry but then fails with the exception.
    I have tried with a generic loop but this doesn't initialise the sub entity so the loop fails and is ignored leading to problems later in the code.
    BwView view = svci.getViewsHandler().find("Lists");
                  BwSubscription[] subarr = (BwSubscription[])view.getSubscriptions().toArray(new BwSubscription []{});
                  if (subarr == null) {
                       logger.info("Its not working");
                  for (int i=subarr.length - 1; i>=0; i--) {
                       sub = subarr;
                   logger.info("Removing subs " + sub);
                   svci.beginTransaction();
                   svci.getSubscriptionsHandler().delete(sub);
                   logger.info("Deleting calendars :" + sub);
                   svci.endTransaction();
    Sub is either not initialised or gets initialised as 0 causing an ArrayIndexOutofBoundsException. I'd be grateful for some advice on getting the code to loop correctly.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    While iterating over a collection (using its iterator), a ConcurrentModificationException will be thrown if the collection is modified, except if it is modified using the iterator itself.. The enhanched for-loop you're using is iterating over the collection by implicitly using an Iterator. To do what you want, make the Iterator explicit (change the enhanced for-loop to a while loop) and then use iterator.remove().

  • ConcurrentModificationException while running the deployed application

    Hi,
    I am using JDeveloper 11.1.2.0.0 and WebLogic Server Version: 10.3.5.0 with production environment.
    My application is based on Customized Dynamic Tab Shell where each task flow is loaded with its own transaction and also it is defined not to share data control.
    I use a Collection Object inside TabContext class, which will be accessed and consumed (including modifications) by all dynamic tab loaded taskflow.
    I use Customized FactoryClass for every BC4JDataControl to track the request and also to pass parameter to model layer AMs
    When i run the application in local, i didn't get any error. But when i check the deployed application, I am getting ConcurrentModificationException frequently as javascript dialog
    java.util.ConcurrentModificationException
    ADF_FACES-60097: For more information, please see the server's error log for
    an entry beginning with: ADF_FACES-60096:Server Exception during PPR, #181When i check the server error log, it didn't say anything about my classes.
    [2011-10-04T01:35:33.608-07:00] [MDA1-Server01] [ERROR] [] [oracle.adfinternal.view.faces.config.rich.RegistrationConfigurator] [tid: [ACTIVE].ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'] [userId: <anonymous>] [ecid: 11d1def534ea1be0:-38985633:132c98ea02d:-8000-000000000000b88b,0] [APP: CalwinApplication] ADF_FACES-60096:Server Exception during PPR, #55[[
    java.util.ConcurrentModificationException
         at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
         at java.util.AbstractList$Itr.next(AbstractList.java:343)
         at org.apache.myfaces.trinidad.render.CoreRenderer.encodeAllChildren(CoreRenderer.java:619)
         at oracle.adf.view.rich.render.RichRenderer.encodeAllChildrenInContext(RichRenderer.java:3062)
         at oracle.adfinternal.view.faces.renderkit.rich.PageTemplateRenderer.encodeAll(PageTemplateRenderer.java:69)
         at oracle.adf.view.rich.render.RichRenderer.encodeAll(RichRenderer.java:1452)
         at org.apache.myfaces.trinidad.render.CoreRenderer.encodeEnd(CoreRenderer.java:493)
         at org.apache.myfaces.trinidad.component.UIXComponentBase.encodeEnd(UIXComponentBase.java:913)
         at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1661)
         at org.apache.myfaces.trinidad.render.CoreRenderer.encodeChild(CoreRenderer.java:607)
         at oracle.adf.view.rich.render.RichRenderer.encodeChild(RichRenderer.java:3201)
         at org.apache.myfaces.trinidad.render.CoreRenderer.encodeAllChildren(CoreRenderer.java:623)
         at oracle.adf.view.rich.render.RichRenderer.encodeAllChildrenInContext(RichRenderer.java:3062)
         at oracle.adfinternal.view.faces.renderkit.rich.RegionRenderer._encodeChildren(RegionRenderer.java:310)
         at oracle.adfinternal.view.faces.renderkit.rich.RegionRenderer.encodeAll(RegionRenderer.java:186)
         at oracle.adf.view.rich.render.RichRenderer.encodeAll(RichRenderer.java:1452)
         at org.apache.myfaces.trinidad.render.CoreRenderer.encodeEnd(CoreRenderer.java:493)
         at org.apache.myfaces.trinidad.component.UIXComponentBase.encodeEnd(UIXComponentBase.java:913)
         at oracle.adf.view.rich.component.fragment.UIXRegion.encodeEnd(UIXRegion.java:323)
         at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1661)
         at org.apache.myfaces.trinidad.component.UIXGroup.encodeChildren(UIXGroup.java:170)
                    .....On checking further about this error code in Oracle® Fusion Middleware Error Messages Reference 11g Release 2 (11.1.2.0.0), it is given as
      ADF_FACES-60097: For more information, please see the server's error log for an
    entry beginning with: {0}
    Cause: An exception was thrown durring a PPR request.
    Action: Please look in the servers error log for more details on this error.
    Level: 1
    Type: ERROR
    Impact: LoggingI couldn't get any hint on what may be the issue. Can anyone help on this?
    Thanks in Advance.
    Perumal S

    I've seen this happen before if component objects are stored in managed beans (e.g. using binding="#{someBean.foo}").
    Problems like this can happen if the component is stored directly on the bean as a member variable (most commonly if the bean is application-scoped, session-scoped, or pageFlow-scoped but smaller scopes can exhibit the problem too).
    Usually just referencing the components from the accessors on JSF event objects during an event handlers or using one of the various component searching APIs (e.g. findComponent) can suffice in locating the components dynamically.
    However, if using one of those mechanisms isn't feasible you must use the ComponentReference as the storage mechanism (and follow the caveats noted in its JavaDoc):
    http://www.jarvana.com/jarvana/view/org/apache/myfaces/trinidad/trinidad-api/2.0.0-beta-1/trinidad-api-2.0.0-beta-1-javadoc.jar!/org/apache/myfaces/trinidad/util/ComponentReference.html
    Hope this helps,
    Matt

  • Iterator.next() throws java.util.ConcurrentModificationException

    Hello, I have a set and an iterator defined like this:
    HashSet<JFrame> set = new HashSet<JFrame>();
    Iterator<JFrame> iterator = set.iterator();
    Then later I add frames like this:
    set.add(jFrame);
    Then later when I try to call:
    iterator.next();
    I get ConcurrentModificationException. But I only call this next() method one time and only.
    I can call hasNext() method without a problem, but not next().
    How do I call next() without an exception??
    Mark

    create an iterator and then after this you change the collection? does this sound safe?(...)after getting the iterator, don't modify the set (with exception as per api) and expect the iterator to work.
    Well, I think you are making fun of me here. It's OK, I don't mind, but I want to disagree with your reasons.
    "Does this sound safe?" Yes, why not? The iterator could refer to the set, whatever its contents. You could add to the set and, and then remove from it by iterator.next(), and add and remove... As long as you synchronise all these things (and I do), there is no general reason why this would be a bad thing.
    But of course, the API does prohibit that explicitly, you are right. It's just that when you naturally expect certain behaviour, you don't read all of the documentation.
    And then when ConcurrentModificationException happens, this exception name does not reflect what happens, as I said, I am not concurrently modifying anything in multiple threads. So the name of the exception threw me off track and I did not think it was the order of the operations that I did wrong.
    Anyway, thank you very much for help.

  • ConcurrentModificationException in WL 7.04 and 7.05

    Help!
              We are porting our application from WL 6.1 to 7.04 (also reproduced in 7.05)
              and are seeing exactly the stack trace listed by Guido and Paul a month or
              so ago -- ConcurrentModificationException called from
              TxManager.flushModifiedBeans(). I have not seen a reply -- can anyone help
              by suggesting what sorts of things we should be looking for in our code?
              Thanks,
              Steve
              Subject: Re: ConcurrentModificationException - Bug in 8.1 SP2 ?
              Date: 15 Mar 2004 02:41:29 -0800
              From: "Paul Davis"
              <[email protected]>
              Organization: BEA NEWS SITE
              Newsgroup: weblogic.developer.interest.transaction
              "Guido Reiff"
              <[email protected]wsgroups.b
              ea.com> wrote:
              >
              >Hello, we developed an application base on BEA Weblogic Server 6.1, that
              >should
              >be migrated to 8.1.
              >There are only stateless Session Beans and BMP Entity Beans (EJB 2.0
              >without the
              >use of Local Home-Interfaces, all Methods with transaction Required).
              >With 6.1
              >we've got no Problems but we get ConcurrentModificationException with
              >8.1, deep
              >within BEA Weblogic Server. It is reproducible but I had no luck to put
              >it into
              >a small example by now. I think this is a bug in 8.1 but I can't believe
              >that
              >I'm the first one to find.
              Guido
              We have an identical issue with an app ported from WLS 6.1 SP5 to 7.0 SP4.
              If you do get any insight on this, please post it here.
              FWIW, our stack trace is:
              ####<12-Mar-04 11:41:10 GMT> <Info> <EJB> <CI069040> <WorksuiteServer>
              <ExecuteThread: '11' for queue: 'default'> <kernel identity>
              <1698:6e6c8348456383de> <010049> <EJB Exception in method: ejbFindList:
              java.util.ConcurrentModificationException>
              java.util.ConcurrentModificationException at
              java.util.HashMap$HashIterator.next(HashMap.java:731) at
              weblogic.ejb20.internal.TxManager.flushModifiedBeans(TxManager.java:328) at
              weblogic.ejb20.manager.BaseEntityManager.flushModifiedBeans(BaseEntityManage
              r.java:1644) at
              weblogic.ejb20.manager.BeanManagedPersistenceManager.collectionFinder(BeanMa
              nagedPersistenceManager.java:142) at
              weblogic.ejb20.manager.BaseEntityManager.collectionFinder(BaseEntityManager.
              java:1001) at
              weblogic.ejb20.manager.BaseEntityManager.collectionFinder(BaseEntityManager.
              java:973) at
              weblogic.ejb20.internal.EntityEJBHome.finder(EntityEJBHome.java:557) at
              com.stsjava.ws.wo.aardvark.ConfigurationItemBMP_w0wzb_HomeImpl.findList(Conf
              igurationItemBMP_w0wzb_HomeImpl.java:126) at
              com.stsjava.ws.wo.scheduling.impl.ScheduledItemBMPImpl.getRoadWorksConfig(Sc
              heduledItemBMPImpl.java:599) at
              com.stsjava.ws.wo.scheduling.impl.ScheduledItemBMPImpl.updateWorkPacket(Sche
              duledItemBMPImpl.java:3357) at
              com.stsjava.ws.wo.scheduling.impl.ScheduledItemBMPImpl.ejbCreateSchedule(Sch
              eduledItemBMPImpl.java:1372) at
              com.stsjava.ws.wo.scheduling.ScheduledItemBMP.ejbCreateSchedule(ScheduledIte
              mBMP.java:246) at
              com.stsjava.ws.wo.scheduling.ScheduledItemBMP_u0iaps_Impl.ejbCreateSchedule(
              ScheduledItemBMP_u0iaps_Impl.java:333) at
              java.lang.reflect.Method.invoke(Native Method) at
              weblogic.ejb20.manager.DBManager.create(DBManager.java:925) at
              weblogic.ejb20.manager.DBManager.remoteCreate(DBManager.java:895) at
              weblogic.ejb20.internal.EntityEJBHome.create(EntityEJBHome.java:244) at
              com.stsjava.ws.wo.scheduling.ScheduledItemBMP_u0iaps_HomeImpl.createSchedule
              (ScheduledItemBMP_u0iaps_HomeImpl.java:194) at
              com.stsjava.ws.wo.task.impl.WorkPacketEJBImpl.schedule(WorkPacketEJBImpl.jav
              a:2830) at
              com.stsjava.ws.wo.task.WorkPacketEJB.schedule(WorkPacketEJB.java:545) at
              com.stsjava.ws.wo.task.WorkPacketBMP_gf17h5_EOImpl.schedule(WorkPacketBMP_gf
              17h5_EOImpl.java:1364) at
              com.stsjava.ws.wo.completion.impl.CompletionServicesCompleteWorkPacketImpl.r
              equestCompletion(CompletionServicesCompleteWorkPacketImpl.java:1429) at
              com.stsjava.ws.wo.completion.impl.CompletionServicesCompleteWorkPacketImpl.e
              xecute(CompletionServicesCompleteWorkPacketImpl.java:328) at
              com.stsjava.ws.wo.completion.impl.CompletionServicesCompleteWorkPacketListIm
              pl.execute(CompletionServicesCompleteWorkPacketListImpl.java:145) at
              com.stsjava.ws.wo.completion.CompletionServicesBean.completeWorkPacketList(C
              ompletionServicesBean.java:259) at
              com.stsjava.ws.wo.completion.CompletionServicesBean_m92hs6_EOImpl.completeWo
              rkPacketList(CompletionServicesBean_m92hs6_EOImpl.java:154) at
              com.stsjava.ws.wo.completion.CompletionServicesBean_m92hs6_EOImpl_WLSkel.inv
              oke(Unknown Source) at
              weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:441) at
              weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.java
              :114) at
              weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:382) at
              weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManage
              r.java:726) at
              weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:377)
              at
              weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:3
              0) at
              weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:234) at
              weblogic.kernel.ExecuteThread.run(ExecuteThread.java:210)
              Cheers
              Paul D
              

    contact [email protected] this might be related to CR094073 I am not
              completely sure but it surely seems like a WLS bug so if its not really
              related support can file a bug report for you.
              sree
              "Senthil Natarajan" <[email protected]> wrote in message
              news:40d9788b$1@mktnews1...
              >
              > Suggestion Pls!
              >
              > We are porting our application from WL 6.1 to 7.0 SP4 and are seeing
              exactly the
              > stack trace listed by Guido and Paul -- ConcurrentModificationException
              called
              > from
              > TxManager.flushModifiedBeans(). I have not seen a reply. Can anyone help
              by suggesting
              > what sorts of things we should be looking for in our code?
              >
              > Thanks,
              >
              > Senthil
              >
              > "Steve Tynor" <[email protected]> wrote:
              > >Help!
              > >
              > >We are porting our application from WL 6.1 to 7.04 (also reproduced in
              > >7.05)
              > >and are seeing exactly the stack trace listed by Guido and Paul a month
              > >or
              > >so ago -- ConcurrentModificationException called from
              > >TxManager.flushModifiedBeans(). I have not seen a reply -- can anyone
              > >help
              > >by suggesting what sorts of things we should be looking for in our code?
              > >
              > >Thanks,
              > >Steve
              > >
              > >
              > >Subject: Re: ConcurrentModificationException - Bug in 8.1 SP2 ?
              > >Date: 15 Mar 2004 02:41:29 -0800
              > >From: "Paul Davis"
              > ><[email protected]>
              > >Organization: BEA NEWS SITE
              > >Newsgroup: weblogic.developer.interest.transaction
              > >
              > >"Guido Reiff"
              >
              ><[email protected]wsgroups.
              b
              > >ea.com> wrote:
              > >>
              > >>Hello, we developed an application base on BEA Weblogic Server 6.1,
              > >that
              > >>should
              > >>be migrated to 8.1.
              > >>There are only stateless Session Beans and BMP Entity Beans (EJB 2.0
              > >>without the
              > >>use of Local Home-Interfaces, all Methods with transaction Required).
              > >>With 6.1
              > >>we've got no Problems but we get ConcurrentModificationException with
              > >>8.1, deep
              > >>within BEA Weblogic Server. It is reproducible but I had no luck to
              > >put
              > >>it into
              > >>a small example by now. I think this is a bug in 8.1 but I can't believe
              > >>that
              > >>I'm the first one to find.
              > >
              > >Guido
              > >
              > >We have an identical issue with an app ported from WLS 6.1 SP5 to 7.0
              > >SP4.
              > >If you do get any insight on this, please post it here.
              > >
              > >FWIW, our stack trace is:
              > >
              > >####<12-Mar-04 11:41:10 GMT> <Info> <EJB> <CI069040> <WorksuiteServer>
              > ><ExecuteThread: '11' for queue: 'default'> <kernel identity>
              > ><1698:6e6c8348456383de> <010049> <EJB Exception in method: ejbFindList:
              > >java.util.ConcurrentModificationException>
              > >java.util.ConcurrentModificationException at
              > > java.util.HashMap$HashIterator.next(HashMap.java:731) at
              > > weblogic.ejb20.internal.TxManager.flushModifiedBeans(TxManager.java:328)
              > >at
              > >
              >
              >weblogic.ejb20.manager.BaseEntityManager.flushModifiedBeans(BaseEntityManag
              e
              > >r.java:1644) at
              > >
              >
              >weblogic.ejb20.manager.BeanManagedPersistenceManager.collectionFinder(BeanM
              a
              > >nagedPersistenceManager.java:142) at
              > >
              >
              >weblogic.ejb20.manager.BaseEntityManager.collectionFinder(BaseEntityManager
              > >java:1001) at
              > >
              >
              >weblogic.ejb20.manager.BaseEntityManager.collectionFinder(BaseEntityManager
              > >java:973) at
              > > weblogic.ejb20.internal.EntityEJBHome.finder(EntityEJBHome.java:557)
              > >at
              > >
              >
              >com.stsjava.ws.wo.aardvark.ConfigurationItemBMP_w0wzb_HomeImpl.findList(Con
              f
              > >igurationItemBMP_w0wzb_HomeImpl.java:126) at
              > >
              >
              >com.stsjava.ws.wo.scheduling.impl.ScheduledItemBMPImpl.getRoadWorksConfig(S
              c
              > >heduledItemBMPImpl.java:599) at
              > >
              >
              >com.stsjava.ws.wo.scheduling.impl.ScheduledItemBMPImpl.updateWorkPacket(Sch
              e
              > >duledItemBMPImpl.java:3357) at
              > >
              >
              >com.stsjava.ws.wo.scheduling.impl.ScheduledItemBMPImpl.ejbCreateSchedule(Sc
              h
              > >eduledItemBMPImpl.java:1372) at
              > >
              >
              >com.stsjava.ws.wo.scheduling.ScheduledItemBMP.ejbCreateSchedule(ScheduledIt
              e
              > >mBMP.java:246) at
              > >
              >
              >com.stsjava.ws.wo.scheduling.ScheduledItemBMP_u0iaps_Impl.ejbCreateSchedule
              > >ScheduledItemBMP_u0iaps_Impl.java:333) at
              > > java.lang.reflect.Method.invoke(Native Method) at
              > > weblogic.ejb20.manager.DBManager.create(DBManager.java:925) at
              > > weblogic.ejb20.manager.DBManager.remoteCreate(DBManager.java:895) at
              > > weblogic.ejb20.internal.EntityEJBHome.create(EntityEJBHome.java:244)
              > >at
              > >
              >
              >com.stsjava.ws.wo.scheduling.ScheduledItemBMP_u0iaps_HomeImpl.createSchedul
              e
              > >(ScheduledItemBMP_u0iaps_HomeImpl.java:194) at
              > >
              >
              >com.stsjava.ws.wo.task.impl.WorkPacketEJBImpl.schedule(WorkPacketEJBImpl.ja
              v
              > >a:2830) at
              > > com.stsjava.ws.wo.task.WorkPacketEJB.schedule(WorkPacketEJB.java:545)
              > >at
              > >
              >
              >com.stsjava.ws.wo.task.WorkPacketBMP_gf17h5_EOImpl.schedule(WorkPacketBMP_g
              f
              > >17h5_EOImpl.java:1364) at
              > >
              >
              >com.stsjava.ws.wo.completion.impl.CompletionServicesCompleteWorkPacketImpl.
              r
              > >equestCompletion(CompletionServicesCompleteWorkPacketImpl.java:1429)
              > >at
              > >
              >
              >com.stsjava.ws.wo.completion.impl.CompletionServicesCompleteWorkPacketImpl.
              e
              > >xecute(CompletionServicesCompleteWorkPacketImpl.java:328) at
              > >
              >
              >com.stsjava.ws.wo.completion.impl.CompletionServicesCompleteWorkPacketListI
              m
              > >pl.execute(CompletionServicesCompleteWorkPacketListImpl.java:145) at
              > >
              >
              >com.stsjava.ws.wo.completion.CompletionServicesBean.completeWorkPacketList(
              C
              > >ompletionServicesBean.java:259) at
              > >
              >
              >com.stsjava.ws.wo.completion.CompletionServicesBean_m92hs6_EOImpl.completeW
              o
              > >rkPacketList(CompletionServicesBean_m92hs6_EOImpl.java:154) at
              > >
              >
              >com.stsjava.ws.wo.completion.CompletionServicesBean_m92hs6_EOImpl_WLSkel.in
              v
              > >oke(Unknown Source) at
              > > weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:441)
              > >at
              > >
              >
              >weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.jav
              a
              > >:114) at
              > > weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:382)
              > >at
              > >
              >
              >weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManag
              e
              > >r.java:726) at
              > >
              weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:377)
              > >at
              > >
              >
              >weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:
              3
              > >0) at
              > > weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:234) at
              > > weblogic.kernel.ExecuteThread.run(ExecuteThread.java:210)
              > >
              > >
              > >Cheers
              > >
              > >Paul D
              > >
              > >
              >
              

  • ConcurrentModificationException when removing from hashmap

    Why when i remove an object from a HashMap in an iterator loop, i get: ConcurrentModificationException, in the call to Next()???
    This is the code:
    HashMap mapa;
    Object temp=null;
    Set keys=mapa.keySet();
    for(Iterator iter=keys.iterator();iter.hasNext();cont++){
    Object key=iter.next(); //getting an exception here after calling remove
    temp=mapa.get(key);
    SomeClass.process($temp);
    mapa.remove(key);
    is there a way to remove each object after i process it (to free memory)?

    DrLaszloJamf wrote:
    Exactly, what i think is , iter.remove() will remove the reference , but mapa.remove(key) will remove the reference and the object too, won't it?We seem to be talking around in circles, but I will give it another try:
    iter.remove() removes the (key, value) entry from the map (of the key last returned by iter.next()).
    mapa.remove(key) removes the (key, value) entry from the map (of the given key).Ok, i get it. The thing is that in the profiler , the number of objects doen't seem to decrease while i'm removin the objects while looping the hashmap, that's why i t thought it wasn't working, but i print the number of items left int the hashmap and it is decreasing....

  • Java synchronization mechanism allows two threads to hold the same lock?

    Dear all,
    I am a little bit puzzled since I cannot explain why I get the following behavior.
    I have a small Java program to draw components. The drawings are cached in the memory for performance improvements. The cache is access by two different threads. Now the funny thing: even I synchronized every access to the cache, I still get ConcurrentModificationExceptions.
    Here is a part of the code:
         @Override public void paint(Graphics g2) {
              // Check if the image is in the cache
              Image drawing;
              synchronized (m_Cache) { drawing = m_Cache.get(m_CurrentOffset); }
              if (drawing == null) {
                   // The image is not cached, so draw it
                   // Put the image into the cache
                   synchronized (m_Cache) { m_Cache.put(m_CurrentOffset, drawing); }
         public void componentResized(ComponentEvent e) {
              // Upon resizing of the component, adjust several pre-calculated values
              // And flush the cache
              synchronized (m_Cache) { m_Cache.clear(); }
         public void elementUpdated(IHexGridElement Element) {
              // Clear cache where the element may be contained at
              synchronized (m_Cache) { for (Point p : m_Cache.keySet()) { if (isElementInScope(Element.getIndex(), p, new Point(p.x + m_MaxColumn, p.y + m_MaxRow))) { m_Cache.remove(p); } } }
         }The paint and componentResized methods are invoked by the AWTEventQueue-0 thread. The elementUpdated method is invoked by "MyThread" thread.
    Now my question is why do I get java.util.ConcurrentModificationException, especially in situations where a lot of repaintings have to be done and the window is resized? When I remove the caching stuff, everything works perfect, but only a little bit slow.
    Thanks for any help.

    In your elementUpdated method, you are using an Iterator to walk over the set of keys in your map. You can't see the Iterator, because you are using the new for-each loop syntax which hides it from you - but it's there under the covers. You are then removing elements from your map directly. This is what causes your ConcurrentModificationException.
    You should re-write your loop to explicitly use an iterator, and then do your remove operation through the iterator.
    Incidentally, you have a slight race condition in your paint method. Two (or more) threads could simultaneously discover that a given image is not cached, then both draw it, then both cache it. If the drawing operation produces the same drawing every time, then the only problem this causes is the overhead of drawing the image multiple times. To fix this, wrap the get, draw and put operations in a single synchronized block.

  • Message queue like in C++ threads

    Hi,
    I have a question. Does java support threads sending messages to each other like in C++ threads on Windows?
    On Win32, a thread sends message to another thread. This message gets queued up in a message queue, I think, by the OS. The receiver thread can Peek or Get a message from the message queue by doing a such a request.
    Thanks.
    Tri

    That code does not check my "claim". You never directly modify the list in that code. This code does verify my "claim" ... lol
    import java.util.*;
    public class test {
    public static void main(String[] args) {
      List list = new LinkedList();
      list.add(new Object());
      Iterator itr = list.iterator();
      list.add(new Object());
      itr.next();
    }Save compile it.. run it... you'll get ConcurrentModificationException. This isn't a "claim" of mine. Iterators in java are what's called "Fail Fast". This means if you directly modify the underlying collection, then try to use the iterator again, it fails, in java with an Exception.
    In your code you posted above you had a "list.add(p);" that's a direct modification of the list. Once that happens, all iterators are invalid, and will throw an exception if used. With more then one thread this can get kinda weird. That's why Doug Lea has created the util.concurrent package. Check out the read write locks. You can put them over a collection with just a few lines of code. Much faster then fully synchronized collections. This package will appear in java version 1.5 ... check out JSR 166. Links inside the site below.. for more info.
    http://g.cs.oswego.edu

  • Using Iterator

    My intention here is to implement a function that do something to a Collection. The function recusively "knock off" one element from the Collection and call recursively until it hits certain base case. Also, I would like my Collection argument untouched (order is not a concern, but at least all the element are there on return). Here is a test:
    import java.util.*;
    public class Test
         public static void test (Collection c) {
              for (Iterator iter=c.iterator(); iter.hasNext(); ) {
                   Object b=iter.next();
                   iter.remove();
                   // revursively, do something with the
                   // ``tail'' of the collection.
                   c.add(b);     // cause ConcurrentModificationException
         public static void main(String argv[]) {
              LinkedList lst = new LinkedList();
              for (int i=0;i<10;i++) {
                   lst.add (new Integer(i));
              System.out.println("Before: " + lst);
              test (lst);
              System.out.println("After: " + lst);
    }I get ConcurrentModificationException and I understand that the problem is that I add within a Iterator loop.
    If I remove the line:
    c.add(b);my original list will be empty. How is this properly done? Thanks in advance.

    You could create a new collection, rather than
    modifying the existing one.My idea here is to avoid allocating and copying new
    Collection.Don't worry about that. And you wouldn't be copying
    it any more than you are now (you'd just be calling
    add() on a different object).Good point here, I wasn't aware of this.
    >
    I need the remove as in the recursive step,What are you don't that's recursive? You referred to
    recursion in a comment but what are you actually
    doing?
    I would
    like to call the same function to the original listof
    elements except for the one I have removed.So you're removing an element from the list, then
    calling the same method recursively, which then also
    removes an element, etc.? Are you doing a
    combinatorics problem or something?Yes I am trying to find all the possible combination of an arbitrary collection of certain size 0<k<=c.size().
    Thanks, I will go with backing up the Collection argument option.

  • 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.

  • Hash-based collections vs. mutable hashcodes

    I've been getting ConcurrentModificationExceptions on HashTables (derivatives) in a single-threaded app that does no overt mods to the collection being iterated. The algorithm is a classic Observer, iterating all listeners on an event. These listeners are rather heavyweight classes with hashcode() (along with equals()) essentially calculating the current object internal state, which is mutable.
    What I think is going on is that during an event (iteration over the set) a listener state may change, resulting in a changed hashcode(). While this doesn't overtly modify the collection, it may modify something like the internal ordering. i.e. the "old" object would appear to have disappeared since it can no longer be resolved with its current hashcode. Can anyone confirm that this is indeed a possible phenomenon? If so, it raises an interesting general issue.
    Should hashcode() and equals() be built on an immutable subset of state? Assuming logical identity is desirable (i.e. state matters to equality), and hashcode should reflect the result of equals (re: Josh Bloch in EJ (2nd) Item# 8), this seems to dictate that such objects are not viable elements of a hash-based collection. Discussion?

    jverd wrote:
    796912 wrote:
    Should hashcode() and equals() be built on an immutable subset of state? hashCode() should, yes. Or, if it's mutable, then when using a hash-based collection you have to remove and re-add after a change, or possibly remove, change, re-add. Additionally, there's the iteration gotcha that you found that prompted this thread.you definitely have to remove before you change, otherwise remove won't work.
    equals() shouldn't matter. Changing an object's hash can change which bucket it's in, and that's why things get screwed up. The equals() comparison comes into play when doing a linear search of that bucket, so changing state that contributes to equals won't hurt that. not entirely true. changing equals could change the validity of the uniqueness of the set. if you change the equals criteria of an object already in the set so that it is now equal to another object in the set, the set is no longer valid. while this may not break quite as spectacularly as changing the hashcode, it can still do interesting things. for instance, if you add another element such that the hashmap decides to re-hash, one of your now duplicate elements will be silently dropped on the floor. long answer short, don't change hashcode or equals.
    However, in a SortedSet or SortedMap, changing state that contributes to equals() could lead to problems, so the same remove/re-add rules would apply.nope, sorted collections don't use hashcode or equals, they use compareTo/compare. but, the same rules certainly apply to the comparison criteria for the given sorted collection.

  • Synchronized method

    If I have a class property map that is syncronized using Collections.synchronizedMap method. If one user is reading that map via an iterator, while another user tries to add another item to the map, what happens? Is the user prevented from adding another item until the person finishes iterating over the map?
    I am kind of new to Synchronization, so please excuse me if this is an obvious question
    Thanks

    jeff54 wrote:
    If I have a class property map that is syncronized using Collections.synchronizedMap method. If one user is reading that map via an iterator, while another user tries to add another item to the map, what happens?If the iteration is not inside a block that's synced on the map, as the docs indicate it has to be, you'll get ConcurrentModificationException if you're lucky, silent data corruption if you're not, or, possibly, if you're very very lucky, there will be no problem.
    Is the user prevented from adding another item until the person finishes iterating over the map?If you synchronize the iteration like the docs say you're supposed to, then yes no other operation can occur on that map until the iteration is complete.
    EDIT: Per Peter's comments, I assumed "user" meant "thread" here.
    Edited by: jverd on Dec 31, 2009 12:12 PM

  • Implementing an event list, concurrent modification

    Hello,
    I've made a list into which I append events, and process them according to their ordering.
    The problem is that an event processing can cause another event to be appended to this same list. So I get ConcurrentModificationExceptions by the iterator of the list.
    Can somehow avoid the need to copy the event list before iterating over it??
    Any help is very welcomed
    Dimitris

    Can you just set a flag that blocks other events while the list is processing? i.e. on first insert... block events until insert and processing is done, then set it true so future events can be added?
    Rob

Maybe you are looking for

  • Creating a new menu in Adobe Indesign CS2

    Please let me know the process of creating a new menu and capturing a event generated by clicking a menu item of that menu. Need help on creating a plugin, loading it and linking it to the Indesign application.

  • Problem in using NSS fips mode for SunPKCS11

    Hello, I am trying to develop a FIPS compliant application using NSS as security provider for SunPKCS11. But when I was trying to run a simple testing program, I ran into the following problem: - If I have the following providers specified in java.se

  • I cant sign in with my ipad to face time or imassege

    Hi i cant access or sign in to face time or imassege in mini ipad

  • How to search for 'period single space any letter' in find/change

    Hi, i'd like to check my document to make sure that between all periods and first words of a sentence there are not single spaces but double spaces.  Is there a way to search for any instances of single spaces that appear after a period?

  • No sound on .mov files - why?

    I've just got a MacPro running 10.4.11. If I download a .mov file it appears to play perfectly but with no sound. I have Quicktime 7.5 installed. What can I do about this? Thanks, Alex