Throwing ConcurrentModificationException

Hi,
I am implementing an Iterator and wish to throw the ConcurrentMoficationException when the underlying list is modified. I do this by keeping track of modCount variable in the iterator implemention and throw the exception if the modcount has changed after the iterator is created. It works fine on NT and gives runtime
Exception in thread "main" java.lang.IllegalAccessError: try to access
field java.util.AbstractList.modCount from class
oracle.tip.repos.core.driver.AssociationList$ItrHere AssociationList is my implementation of ArrayList.
In the iterator
private class Itr implements Iterator {
int firstModCount = modCount;
public Object next() throws ConcurrentModificationException {
// after the iterator is created list has been modified, throw
// concurrent modified exception
int newModCount = modCount;
if (firstModCount != newModCount)
throw new ConcurrentModificationException();
This code executes in NT 4.0 without any problem only on solaris I get the above runtime exception.
Could this be a bug ?
Any pointers on troubleshooting this problem ?
thanks
Poornima

The comments so far make sense in that it is a scoping issue. It is indeed strange that it is platform-specific. You could perhaps provide a workaround by creating a private accessor method for the iterator implementation to use. Something like
private int getModCount() {
    return modCount;
}should work OK. Then call getModCount in your iterator rather than accessing modCount directly.
I would make your new next() code look like this:
public Object next() throws ConcurrentModificationException {
    if (firstModCount != getModCount()) {
        throw new ConcurrentModificationException();
    /* the rest of your implementation */
}BTW, when you post your code, you might want to use code and /code tags (with square braces around them) in order to preserve your formatting.

Similar Messages

  • Code that consistently throw ConcurrentModificationExceptions?

    I would like to know some code that is definitely thread- unsafe, AND consistently throws ConcurrentModificationExceptions .
    Without bad code that I know is incorrect and gives me feedback (via thrown Exceptions) to fix, I can't get a feel for what needs to be synchronized or if I am synchronizing correctly.
    The scenario I am thinking of would use two, or more, threads and a shared Collection .
    btw: an example of what I mean is java.io.Writer.
    I synchronized access; how would it make sense for 2 threads to share the same writer I assumed. It worked fined. Then, as a test, I removed the synchronization, and it still worked fine. It turns out a Writer is actually synchronized by default. So, I made a big mistake by synchronizing something that was already synchronized.
    Anyway, this is an example of what I mean. I'd hope to know some technique to increase the probablility of getting synchronization errors (especially with shared Collections).
    Thanks.
    Edited by: rdkh on May 31, 2009 7:53 PM

    Hi rdkh,
    for(Integer intObj : IntSet) {
      intSet.remove(intObj);
    }is simply wrong.
    Excerpt from the description of the [*ConcurrentModificationException*|http://java.sun.com/javase/6/docs/api/java/util/ConcurrentModificationException.html] :
    "Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception. "
    Your coding may be simplified this way :
    IntSet.clear();

  • Kodo enhancer throws ConcurrentModificationException

    Attached is the stacktrace i get during enhancement, inside ant build
    process.
    Kodo suddenly fails on classes that were enhanced correctly before, so I
    guess its some internal bug.
    Does anyone know why it happens?
    raczer.
    I use:
    - kodo 2.4.0
    - ant 1.5.1
    begin 666 stacktrace.txt
    M6RXN+ET-"B @(" @6VID;V-=(&IA=F$N=71I;"Y#;VYC=7)R96YT36]D:69I
    M8V%T:6]N17AC97!T:6]N#0H@(" @(%MJ9&]C72 @(" @870@:F%V82YU=&EL
    M+E1R965-87 D16YT<GE)=&5R871O<BYN97AT16YT<GDH5')E94UA<"YJ879A
    M.C$P,C(I#0H@(" @(%MJ9&]C72 @(" @870@:F%V82YU=&EL+E1R965-87 D
    M2V5Y271E<F%T;W(N;F5X="A4<F5E36%P+FIA=F$Z,3 T-RD-"B @(" @6VID
    M;V-=(" @("!A="!C;VTN<V]L87)M971R:6,N:V]D;RYM971A+D-L87-S365T
    M841A=&$N9FEN:7-H*$-L87-S365T841A=&$N:F%V83HS-#4I#0H@(" @(%MJ
    M9&]C72 @(" @870@8V]M+G-O;&%R;65T<FEC+FMO9&\N;65T82Y#;&%S<TUE
    M=&%$871A+FYE=TEN<W1A;F-E*$-L87-S365T841A=&$N:F%V83HR-C@I#0H@
    M(" @(%MJ9&]C72 @(" @870@8V]M+G-O;&%R;65T<FEC+FMO9&\N;65T82Y#
    M;&%S<TUE=&%$871A+F=E=$EN<W1A;F-E*$-L87-S365T841A=&$N:F%V83HQ
    M.3(I#0H@(" @(%MJ9&]C72 @(" @870@8V]M+G-O;&%R;65T<FEC+FMO9&\N
    M;65T82Y#;&%S<TUE=&%$871A+G9A;&ED871E4W5P97)C;&%S<RA#;&%S<TUE
    M=&%$871A+FIA=F$Z-#0V*0T*(" @("!;:F1O8UT@(" @(&%T(&-O;2YS;VQA
    M<FUE=')I8RYK;V1O+FUE=&$N0VQA<W--971A1&%T82YF:6YI<V@H0VQA<W--
    M971A1&%T82YJ879A.C,S,RD-"B @(" @6VID;V-=(" @("!A="!C;VTN<V]L
    M87)M971R:6,N:V]D;RYM971A+D-L87-S365T841A=&$N;F5W26YS=&%N8V4H
    M0VQA<W--971A1&%T82YJ879A.C(V."D-"B @(" @6VID;V-=(" @("!A="!C
    M;VTN<V]L87)M971R:6,N:V]D;RYM971A+D-L87-S365T841A=&$N9V5T26YS
    M=&%N8V4H0VQA<W--971A1&%T82YJ879A.C$Y,BD-"B @(" @6VID;V-=(" @
    M("!A="!C;VTN<V]L87)M971R:6,N:V]D;RYE;FAA;F-E+DI$3T5N:&%N8V5R
    M+CQI;FET/BA*1$]%;FAA;F-E<BYJ879A.C(R-"D-"B @(" @6VID;V-=(" @
    M("!A="!C;VTN<V]L87)M971R:6,N:V]D;RYE;FAA;F-E+DI$3T5N:&%N8V5R
    M+F5N:&%N8V4H2D1/16YH86YC97(N:F%V83HQ.#<I#0H@(" @(%MJ9&]C72 @
    M(" @870@8V]M+G-O;&%R;65T<FEC+FMO9&\N96YH86YC92Y*1$]%;FAA;F-E
    M<BYE;FAA;F-E*$I$3T5N:&%N8V5R+FIA=F$Z,3,U*0T*(" @("!;:F1O8UT@
    M(" @(&%T(&-O;2YS;VQA<FUE=')I8RYM;V1U;&5S+FEN=&5G<F%T:6]N+F%N
    M="Y*1$]%;FAA;F-E<E1A<VLN97AE8W5T94]N*$I$3T5N:&%N8V5R5&%S:RYJ
    M879A.C0S*0T*(" @("!;:F1O8UT@(" @(&%T(&-O;2YS;VQA<FUE=')I8RYM
    M;V1U;&5S+FEN=&5G<F%T:6]N+F%N="Y487-K0F%S92YE>&5C=71E*%1A<VM"
    M87-E+FIA=F$Z,3$X*0T*(" @("!;:F1O8UT@(" @(&%T(&]R9RYA<&%C:&4N
    M=&]O;',N86YT+E5N:VYO=VY%;&5M96YT+F5X96-U=&4H56YK;F]W;D5L96UE
    M;G0N:F%V83HQ-C8I#0H@(" @(%MJ9&]C72 @(" @870@;W)G+F%P86-H92YT
    M;V]L<RYA;G0N5&%S:RYP97)F;W)M*%1A<VLN:F%V83HS,3DI#0H@(" @(%MJ
    M9&]C72 @(" @870@;W)G+F%P86-H92YT;V]L<RYA;G0N5&%R9V5T+F5X96-U
    M=&4H5&%R9V5T+FIA=F$Z,S Y*0T*(" @("!;:F1O8UT@(" @(&%T(&]R9RYA
    M<&%C:&4N=&]O;',N86YT+E1A<F=E="YP97)F;W)M5&%S:W,H5&%R9V5T+FIA
    M=F$Z,S,V*0T*(" @("!;:F1O8UT@(" @(&%T(&]R9RYA<&%C:&4N=&]O;',N
    M86YT+E!R;VIE8W0N97AE8W5T951A<F=E="A0<F]J96-T+FIA=F$Z,3,P-BD-
    M"B @(" @6VID;V-=(" @("!A="!O<F<N87!A8VAE+G1O;VQS+F%N="Y0<F]J
    M96-T+F5X96-U=&5487)G971S*%!R;VIE8W0N:F%V83HQ,C4P*0T*(" @("!;
    M:F1O8UT@(" @(&%T(&]R9RYA<&%C:&4N=&]O;',N86YT+DUA:6XN<G5N0G5I
    M;&0H36%I;BYJ879A.C8Q,"D-"B @(" @6VID;V-=(" @("!A="!O<F<N87!A
    M8VAE+G1O;VQS+F%N="Y-86EN+G-T87)T*$UA:6XN:F%V83HQ.38I#0H@(" @
    M(%MJ9&]C72 @(" @870@;W)G+F%P86-H92YT;V]L<RYA;G0N36%I;BYM86EN
    H*$UA:6XN:F%V83HR,S4I#0H-"D)524Q$($9!24Q%1 T*6RXN+ET-"@``
    `
    end

    This sounds like a manifestation of
    http://bugzilla.solarmetric.com/show_bug.cgi?id=472 to me. Do you have
    circular dependencies between classes defined in multiple metadata
    files? For example, do you have a class Foo whose metadata is defined in
    Foo.jdo, and a class Bar whose metadata is in Bar.jdo, and do Foo and
    Bar have references to each other?
    If this is the bug, the only current workaround is to put those classes
    that have circular references into the same metadata file (a package.jdo
    file or a system.jdo file).
    -Patrick
    Rafa__ Czerwi__ski wrote:
    Attached is the stacktrace i get during enhancement, inside ant build
    process.
    Kodo suddenly fails on classes that were enhanced correctly before, so I
    guess its some internal bug.
    Does anyone know why it happens?
    raczer.
    I use:
    - kodo 2.4.0
    - ant 1.5.1
    [jdoc] java.util.ConcurrentModificationException
    [jdoc] at
    java.util.TreeMap$EntryIterator.nextEntry(TreeMap.java:1022)
    [jdoc] at java.util.TreeMap$KeyIterator.next(TreeMap.java:1047)
    [jdoc] at
    com.solarmetric.kodo.meta.ClassMetaData.finish(ClassMetaData.java:345)
    [jdoc] at
    com.solarmetric.kodo.meta.ClassMetaData.newInstance(ClassMetaData.java:268)
    [jdoc] at
    com.solarmetric.kodo.meta.ClassMetaData.getInstance(ClassMetaData.java:192)
    [jdoc] at
    com.solarmetric.kodo.meta.ClassMetaData.validateSuperclass(ClassMetaData.java:446)
    [jdoc] at
    com.solarmetric.kodo.meta.ClassMetaData.finish(ClassMetaData.java:333)
    [jdoc] at
    com.solarmetric.kodo.meta.ClassMetaData.newInstance(ClassMetaData.java:268)
    [jdoc] at
    com.solarmetric.kodo.meta.ClassMetaData.getInstance(ClassMetaData.java:192)
    [jdoc] at
    com.solarmetric.kodo.enhance.JDOEnhancer.(JDOEnhancer.java:224)
    [jdoc] at
    com.solarmetric.kodo.enhance.JDOEnhancer.enhance(JDOEnhancer.java:187)
    [jdoc] at
    com.solarmetric.kodo.enhance.JDOEnhancer.enhance(JDOEnhancer.java:135)
    [jdoc] at
    com.solarmetric.modules.integration.ant.JDOEnhancerTask.executeOn(JDOEnhancerTask.java:43)
    [jdoc] at
    com.solarmetric.modules.integration.ant.TaskBase.execute(TaskBase.java:118)
    [jdoc] at
    org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:166)
    [jdoc] at org.apache.tools.ant.Task.perform(Task.java:319)
    [jdoc] at org.apache.tools.ant.Target.execute(Target.java:309)
    [jdoc] at
    org.apache.tools.ant.Target.performTasks(Target.java:336)
    [jdoc] at
    org.apache.tools.ant.Project.executeTarget(Project.java:1306)
    [jdoc] at
    org.apache.tools.ant.Project.executeTargets(Project.java:1250)
    [jdoc] at org.apache.tools.ant.Main.runBuild(Main.java:610)
    [jdoc] at org.apache.tools.ant.Main.start(Main.java:196)
    [jdoc] at org.apache.tools.ant.Main.main(Main.java:235)
    BUILD FAILED
    Patrick Linskey [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • ArrayList throwing ConcurrentModificationException

    Hey everybody,
    Im just goofing around with a little board game display class(my aim is to end up goofing around with A*, but thats still far in the future). Another thing I wanted to implement were little graphics FX. I use an ArrayList to display multiple FX:
    class FX
        abstract void displayTo(Graphics g);
        abstract boolean finished() // has the effect finished its job?
    ArrayList <FX> aL = new ArrayList<FX>();
    for (FX f: aL)
        f.displayTo(getGraphics());
        if(f.finished()) FX.remove(f);
    }Exact message:
    Exception in thread "Thread-2" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
    at java.util.AbstractList$Itr.next(AbstractList.java:343)
    at gcds.TileMap.pumpFX(TileMap.java:44)
    at gcds.TileMap.renderFrame(TileMap.java:39)
    at pup.GCD.step(GCD.java:27)
    at pup.GCD.frame(GCD.java:29)
    at pup.GameCMP.run(GameCMP.java:25)
    at java.lang.Thread.run(Thread.java:619)
    I use a Thread(Runnable ) that paints a BufferedImage on a JPanel. The BufferedImage is being created by a method that calls the above piece of code.
    Thanks for reading through this mess :)
    Edit: I came up with a workaround - filling an ArrayList with Objects that need to be removed after the foreach loop - but I think thats not too elegant.
    Edited by: anotherAikman on Jan 19, 2010 3:44 AM

    anotherAikman wrote:
    Thank you tschodt! Ill give it a try.
    Edit:
    Iterator<FX> it = FX.iterator();
    while(it.hasNext())
    FX m = it.next();
    m.displayTo(getGraphics());
    if(m.finished()) it.remove();
    }seems to work good. Ill try some more things to ensure I understood the iterator logic.No "seems to" about it. That's exactly the fix!

  • 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);
    }

  • Two Iterators on the Same Collection

    I posted this one on the Java Collections Framework forum but there don't seem to be many people there so let me post this here, too.
    I want to use two iterators at the same time on a single collection. They are like two trains going one after another. If I use the iterator supplied by Java, however, if one iterator structurally modifies the underlying collection, the other throws ConcurrentModificationException.I want to avoid this. I want both iterators to modify the underlying collection freely, and when the collection was modified by one, I want the other to know what happened and what to do, rather than throwing an exception. How can I do this? Can I just manipulate somewhat on the Java iterator, or must I make an iterator implementation that does what I want from the scratch?

    I'm writing a flow analysis module of a compiler. I'm not totally sure what optimizer does, but it needs to manipulate the list of instructions, which involves removing and adding instructions into the list. Some time we may need two iterators that cooperate together to find out when we can remove an instruction, for example. Or, one iterator does the analysis and removal, while the other may do some cleanup work. (I say again I'm not totally sure what optimizer does.) Some guy suggested using visitor pattern, but after some investigation (of the visitor pattern stuff) I thought iterator that behaved more smartly was more relevant. Or maybe not.

  • What is the difference between iterator.remove() ArrayList.remove()?

    Following code uses iterator.remove() ArrayList.remove().
    public class CollectionRemove
        private static void checkIteratorRemove()
             List<String> list = new ArrayList<String>();     
              list.add("1");
              list.add("2");
              list.add("3");     
             System.out.println("in checkWithIterator*************");
            Iterator<String> iter = list.iterator();
            while (iter.hasNext()) {
                String str = iter.next();           
                if (str.equals("2")) {
                    iter.remove();
                System.out.println("list Size: " + list.size() + " Element: " +  str);
        private static void checkListRemove()
             List<String> list = new ArrayList<String>();     
              list.add("1");
              list.add("2");
              list.add("3");     
            System.out.println("in ncheckWithForLoop*************");
            Iterator<String> iter = list.iterator();
            while (iter.hasNext()) 
                 String str = (String) iter.next();    
                if (str.equals("2")) {
                    list.remove(str);
                System.out.println("list Size: " + list.size() + " Element: " +  str);
        public static void main(String args[])
             checkIteratorRemove();
             checkListRemove();
    output is :
    in checkWithIterator*************
    list Size: 3 Element: 1
    list Size: 2 Element: 2
    list Size: 2 Element: 3
    in ncheckWithForLoop*************
    list Size: 3 Element: 1
    list Size: 2 Element: 2Why is this difference ? what is the difference between iterator.remove() ArrayList.remove()?

    In the case of Fail-fast iterator, if a thread modifies a collection directly while iterating over it, the iterator will thow ConcurrentModificationException . Say,
    for (Iterator it = collection.iterator(); it.hasNext()) {
        Object object = it.next();
        if (isConditionTrue) {
            // collection.remove(object);  can throw ConcurrentModificationException
            it.remove(object);
    }As per specs,
    Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will thow this exception.

  • Query on using Collection object in Multithreading

    All,
    I have a query on multithreading, I have a collection object-eg. HashMap which needs to be shared
    among threads, I my have 3 options
    1st option is to synchronize the method which does some manipulation on the collection object,
    2nd option is to hold a lock on that object like
    synchronized(object){
    //do some work
    3rd option - to make use of class ConcurrentHashMap available in java.util.concurrent package; which claims to be
    Thread safe but also says the following in the API - They do not throw ConcurrentModificationException. However,
    iterators are designed to be used by only one thread at a time
    My queston is - how do I choose between these 3?
    I know the decison needs to be taken by keeping performance issue in mind and also the number of times the values in HashMap will be updated by the threads. Can some one explain to me when/under what circumstances do I use options 1 || 2 || 3

    My application has actually gone live now - after doing some load/performance testing
    and comming to the conclusion that performance is satisfactory [I am designing a SMS gateway
    that receives/buffers/stores/sends SMS]
    Initially I used Hashmap and a LinkedList to store objects in memory and I had a mixture
    of places where some times I made the entire method that modifies the LinkedList & hashmap
    synchronized and some places where I held a lock on the object alone (I wasnt too sure which to use where)
    Then upon movin to 1.5 I rechanged the the data structure to use ConcurrentLinkedQueue & ConcurrenthashMap.
    But i have places where I still hold synchronized locks over those objects (which i think is unnecessary and removing the locks may improve the performance)
    So can i come to the conclusion that classes in java.util.concurrent are all threadsafe and we can stop holding locks on the objects and let java take care of itself [or should I still hold a lock when doing structural modification] [though the APi states that a oncurrentmodificationexception will not be thrown & iterators are designed to be used by only one thread at a time]

  • ConcurrentHashMap VS. HashTable

    Hi all,
    I need to use a thread-safe map and am not sure if I can safely use java.util.concurrent.ConcurrentHashMap instead of HashTable w/o external synchronization. The Java docs says:
    "A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable.
    *+However, even though all operations are thread-safe, retrieval operations do+ +not+ +entail locking, and there is+ +not+ +any support for locking the entire table in a way that prevents all access. This class is fully interoperable with+ **+Hashtable+** +in programs that rely on its thread safety but not on its synchronization details.+*
    *+Retrieval operations (including+ **+get+**+) generally do not block, so may overlap with update operations (including+ **+put+** +and+ **+remove+**+). Retrievals reflect the results of the most recently+ +completed+ +update operations holding upon their onset. For aggregate operations such as+ **+putAll+** +and+ **+clear+**+, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration+*.
    They do +not+ throw [ConcurrentModificationException|http://java.sun.com/javase/6/docs/api/java/util/ConcurrentModificationExceptio
    *+However, iterators are designed to be used by only one thread at a time.+*"
    I do use iterators on my map; and it will be used by many threads at the same time; so does that mean I need to externally "synchronize" my map?
    The parts in bold and italic made me not sure about using the ConcurrentHashMap...

    JavaFunda wrote:
    So can anybody give a example where we hashtable can not be replace by ConcusrrentHashMapPersonally, other than Peter's first suggestion, I can't think of a single one. I believe that EJP's post (other than line 3) was aimed at why you might prefer a HashMap ( not Hashtable) over CHM; and he's dead right.
    Winston

  • Map in map syncronization

    Hi guys! I'm new to threads so sorry if my question is dumb.
    So here it goes: I was wondering if read/writes from something like this: ConcurrentHashMap<String,ConcurrentHashMap<Integer,ConcurrentHashMap<String,Object>>> are thread safe?
    ConcurrentHashMap offers thread safety without locking wich is preatty cool but i don't think that combining more of them keeps is right. What do you think?
    Thank you!
    Cristian

    cvrabie wrote:
    ConcurrentHashMap offers thread safety without locking wich is preatty cool but i don't think that combining more of them keeps is right. What do you think?
    Thank you!
    CristianWell, it seems not quite true: there is locking in case of concurrent collection classes, but it is implemented in a different way that the one in case of synchronized collection classes. Here is an excerpt from Brian Goetz "Java Concurrency in Practice " book (section "5.2.1. ConcurrentHashMap"):
    "...ConcurrentHashMap is a hash-based Map like HashMap, but it uses an *entirely different locking strategy* that offers better concurrency and scalability. *Instead of synchronizing every method on a common lock*, restricting access to a single thread at a time, *it uses a finer-grained locking mechanism called lock striping* (see Section 11.4.3) to allow a greater degree of shared access..."
    And, btw, this is the reason why concurrent collections are not only "don't throw ConcurrentModificationException", but "not even able" to throw them.

  • HashMap, HashSet and infinite loop

    hi,
    our code ended up in an infinite loop while parsing the entries of a HashMap with this code:
            Iterator it = myHashMap.entrySet().iterator();
            while (it.hasNext()) {
                field = (Map.Entry) it.next();
                // code that access content of "field"
            } as the loop creates some kind of objects, the JVM terminated with a out-of-memory. luckily we got a heap-dump file and that shows:
    - the hash-map has 325 entries
    - the loop was iterated more than 3 million times
    - the iterator "it" has a current and a next field pointing at the same element of the HashMap
    a snapshot of the heap-analysis of the iterator can be seen at
    http://www.sbox.tugraz.at/home/a/archmage/hashset/EntryIterator.html
    maybe the HashMap was accessed concurrently, but then there should be a ConcurrentModificationException.
    we are using
    > java -version
    java version "1.4.2_12"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_12-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_12-b03, mixed mode)for me, this looks like a JVM bug, but i cannot really believe that (and i could not find a bug stating this behaviour).
    is there anything i did not notice during using hashmaps/hashsets/iterators?
    regards, werner

    there should be aConcurrentModificationException.
    Not necessarily. The iterators cannot always detectConcurrentModificationException.
    api-docs of HashMap say:
    A structural modification is any operation that adds
    or deletes one or more mappings
    if the map is structurally modified at any time after
    the iterator is created, in any way except through
    the iterator's own remove or add methods, the
    iterator will throw a
    ConcurrentModificationException.
    for me, that means, the iterator should detect any
    "add" or "delete" operation like map.put(...). am i
    wrong? or are the docs wrong here?Immediately AFTER the paragraph you quoted, it says
    Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html
    Furthermore, did you READ what I said after that?
    It's FAR MORE LIKELY to be a result of data corruption, rather than multiple simultaneous iterators.

  • 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 transactional operations

    I'm trying to do simple puts on a transactional cache with these settings. The puts do not conflict with each other on their keys.
    connection.setAutoCommit(false);
    connection.setIsolationLevel(Isolation.READ_COMMITTED);
    connection.setEager(false);As soon as a few transactions have completed I start seeing these errors. After that all other transactions also fail with confusing exceptions - some about ClassNotFound and some about txns already being committed.
    java.util.ConcurrentModificationException
         at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
         at java.util.AbstractList$Itr.next(AbstractList.java:343)
         at com.tangosol.coherence.transaction.internal.TranscriptImpl.getModifiedTables(TranscriptImpl.java:66)
         at com.tangosol.coherence.transaction.internal.storage.Session.getModifiedTables(Session.java:79)
         at com.tangosol.coherence.transaction.internal.storage.Session.queueOperation(Session.java:35)
         at com.tangosol.coherence.transaction.internal.router.LocalDirector.route(LocalDirector.java:41)
         at com.tangosol.coherence.transaction.internal.Endpoint.dispatch(Endpoint.java:105)
         at com.tangosol.coherence.transaction.internal.OptimisticNamedCacheImpl.invoke(OptimisticNamedCacheImpl.java:708)
         at com.tangosol.coherence.transaction.internal.OptimisticNamedCacheImpl.put(OptimisticNamedCacheImpl.java:370)
    java.lang.IllegalStateException: Operation called in illegal state: COMMITTED
         at com.tangosol.coherence.transaction.internal.TransactionImpl.assertStateChange(TransactionImpl.java:313)
         at com.tangosol.coherence.transaction.internal.TransactionImpl.setCommitted(TransactionImpl.java:140)
         at com.tangosol.coherence.transaction.internal.component.ClientAutoCommit.invoke(ClientAutoCommit.java:76)
         at com.tangosol.coherence.transaction.internal.Endpoint.dispatch(Endpoint.java:95)
         at com.tangosol.coherence.transaction.internal.router.StaticEndpointConcern.apply(StaticEndpointConcern.java:48)
         at com.tangosol.coherence.transaction.internal.router.OperationFilter.apply(OperationFilter.java:51)
         at com.tangosol.coherence.transaction.internal.router.OutboundRouterImpl.route(OutboundRouterImpl.java:36)
         at com.tangosol.coherence.transaction.internal.Endpoint.dispatch(Endpoint.java:105)
         at com.tangosol.coherence.transaction.internal.router.StaticEndpointConcern.apply(StaticEndpointConcern.java:48)
         at com.tangosol.coherence.transaction.internal.router.OperationFilter.apply(OperationFilter.java:51)
         at com.tangosol.coherence.transaction.internal.router.OutboundRouterImpl.route(OutboundRouterImpl.java:36)
         at com.tangosol.coherence.transaction.internal.Endpoint.dispatch(Endpoint.java:105)
         at com.tangosol.coherence.transaction.internal.router.StaticEndpointConcern.apply(StaticEndpointConcern.java:48)
         at com.tangosol.coherence.transaction.internal.router.OperationFilter.apply(OperationFilter.java:51)
         at com.tangosol.coherence.transaction.internal.router.OutboundRouterImpl.route(OutboundRouterImpl.java:36)
         at com.tangosol.coherence.transaction.internal.Endpoint.dispatch(Endpoint.java:105)
         at com.tangosol.coherence.transaction.internal.router.StaticEndpointConcern.apply(StaticEndpointConcern.java:48)
         at com.tangosol.coherence.transaction.internal.router.OperationFilter.apply(OperationFilter.java:51)
         at com.tangosol.coherence.transaction.internal.router.OutboundRouterImpl.route(OutboundRouterImpl.java:36)
         at com.tangosol.coherence.transaction.internal.router.LocalDirector.route(LocalDirector.java:56)
         ... 22 moreSometimes:
    java.lang.IllegalStateException: Operation called in illegal state: ERROR
    ...Any ideas?
    Thanks,
    Ashwin.

    I suppose this is the correct way to use optimistic, transactional caches:
    * Author: Ashwin Jayaprakash / Date: 1/4/12 / Time: 12:32 PM
    public class TxnTest {
        protected static final ThreadLocal<Connection> connections = new ThreadLocal<Connection>();
        protected static DefaultConnectionFactory connectionFactory;
        public static void main(String[] args) throws Exception {
            connectionFactory = new DefaultConnectionFactory();
            for (int i = 0; i < 5; i++) {
                runTest();
        private static void runTest() throws InterruptedException {
            Runnable job = new Runnable() {
                @Override
                public void run() {
                    String name = Thread.currentThread().getName();
                    for (int i = 0; i < 100; i++) {
                        for (int j = 0; j < 3; j++) {
                            if (j > 0) {
                                System.out.printf("Txn [%s-%d] retry attempt [%d]%n", name, i, j);
                            Connection connection = connectionFactory.createConnection();
                            connection.setAutoCommit(false);
                            connection.setIsolationLevel(Isolation.READ_COMMITTED);
                            connection.setEager(false);
                            OptimisticNamedCache users = connection.getNamedCache("tx-users");
                            try {
                                users.put("bill", new User("bill-" + name, i));
                                users.put("mary", new User("mary-" + name, i));
                                users.put("john", new User("john-" + name, i));
                                connection.commit();
                                break;
                            catch (Exception e) {
                                connection.rollback();
                            finally {
                                connection.close();
            Thread t1 = new Thread(job);
            Thread t2 = new Thread(job);
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            System.out.println("Entries: " + CacheFactory.getCache("tx-users").size());
            for (Object o : CacheFactory.getCache("tx-users").values()) {
                System.out.println("   " + o);
        public static class User implements Serializable {
            String name;
            int age;
            public User() {
            public User(String name, int age) {
                this.name = name;
                this.age = age;
            public String getName() {
                return name;
            public int getAge() {
                return age;
            @Override
            public String toString() {
                final StringBuilder sb = new StringBuilder();
                sb.append(getClass().getName());
                sb.append("{name='").append(name).append('\'');
                sb.append(", age=").append(age);
                sb.append('}');
                return sb.toString();
    }

  • Am getting "Caused by: java.util.ConcurrentModificationException"

    Hi,
    I written code as below
    public String createHM2Req(String ReqFileNm) throws Exception
              String retVal="";
              String strId = "";
              try
    System.out.println(" --- LSReqFileNm "+ReqFileNm);
    System.out.println(" -- hmReqData "+hmReqData);
    strId = "TE"+getValHMProcessReq("SubjBorrId");
    if(!getValHMProcessReq("SpouseId").equals("") && getValHMProcessReq("ServiceTypCd").equals("ABCD"))
    strId += " TE"+getValHMProcessReq("SpouseId");
    public String getValHMProcessReq(String key) throws Exception
    String retVal="";
              try
                   if(key != null && !key.equals(""))
                        if(!checkNull(hmReqData.get(key)+"").equals(""))
                             retVal = hmReqData.get(key).toString();
                             retVal = escape(retVal);
              catch(Exception e)
                   e.printStackTrace();
              return retVal;
    In this code I decleared hmReqData as Global Hashmap
    this code is working fine.
    But some times am getting below exception.
    Caused by: java.util.ConcurrentModificationException
         at java.util.HashMap$HashIterator.nextEntry HashMap.java:782)
         at java.util.HashMap$EntryIterator.next(HashMap.java:824)
         at java.util.AbstractMap.toString(AbstractMap.java:586)
         at java.lang.String.valueOf(String.java:2131)
         at java.lang.StringBuffer.append(StringBuffer.java:370)
    can any one help me to solve this problem....
    Please its urgent...
    Thank U
    Vinod

    Hi..
    Sorry for that. But while posting the question for first time, the IE is not responded. I didnt know that it is posted...thats why i posted second time

  • Am getting java.util.ConcurrentModificationException while accessing Hashma

    Hi,
    I written code as below
    public String createHM2Req(String ReqFileNm) throws Exception
              String retVal="";
              String strId = "";
              try
    System.out.println(" --- LSReqFileNm "+ReqFileNm);
    System.out.println(" -- hmReqData "+hmReqData);
    strId = "TE"+getValHMProcessReq("SubjBorrId");
    if(!getValHMProcessReq("SpouseId").equals("") && getValHMProcessReq("ServiceTypCd").equals("ABCD"))
    strId += " TE"+getValHMProcessReq("SpouseId");
    public String getValHMProcessReq(String key) throws Exception
    String retVal="";
              try
                   if(key != null && !key.equals(""))
                        if(!checkNull(hmReqData.get(key)+"").equals(""))
                             retVal = hmReqData.get(key).toString();
                             retVal = escape(retVal);
              catch(Exception e)
                   e.printStackTrace();
              return retVal;
    Am getting below exception at run time
    Caused by: java.util.ConcurrentModificationException
         at java.util.HashMap$HashIterator.nextEntry(HashMap.java:782)
         at java.util.HashMap$EntryIterator.next(HashMap.java:824)
         at java.util.AbstractMap.toString(AbstractMap.java:586)
         at java.lang.String.valueOf(String.java:2131)
         at java.lang.StringBuffer.append(StringBuffer.java:370)

    Something is calling toString on a map and something else is modifying that map. toString will start iterating. You probably get that exception if another request at the same times modifies the map.

Maybe you are looking for