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!

Similar Messages

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

  • 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

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

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

  • Simple java.lang.IndexOutOfBoundsException Question

    Hi, I'm trying to be able to put data into a vector or arraylist without filling the previous spots. Take this for example:
    ArrayList temp=new ArrayList(10);
    temp.ensureCapacity(10);
    temp.set(5, new Integer(5));
    I declaired the size to be 10 twice, why can't I input into the 5th element directly? Is there a way to? I would use normal arrays, but I need to be able to dynamically change the size. I'm having this exact same problem with vectors also. Any ideas? Thank you!

    according to the API specification, the set method of ArrayList:
    Throws:
    IndexOutOfBoundsException - if index out of range (index < 0 || index >= size()).
    size() is the number of elements already inserted.
    Size is not the same as capacity.
    With temp.ensureCapacity(10) you ensure that your ArrayList will be
    able to fit 10 elements without resizing the internal Array, but the
    actual size of the List remains as it was (in your case 0 because you
    haven't inserted anything yet).
    the set method is intended to allow you to change the element at the
    specified index, provided that it has already been inserted in the list.

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

  • Determine the JRE version of a user

    I have 2 versions of an applet (which I didn't write) - one which works on the standard built-in browser JRE, and one with more features but requires the Sun JRE.
    Rather than require that everyone download the Sun JRE, I'd rather write a tiny redirect applet that tells which version they have and redirect to the appropriate page, with a note saying "to get more features download the Sun JRE" and a link or something.
    I know I can do this by something like seeing if Class.forName("java.util.ArrayList"); throws an exception, but that seems hackish and I was wondering if there was a better way?

    Aha! nm, I found it
    System.getProperty("java.vendor");
    System.getProperty("java.version");

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

  • Bind a combo

    Hi experts,
    I am trying to bind a combo to a bean property (an arrayList holding a resulset) - do anyone knw how to go abt it?
    Need your advice experts

    Hi Guys,
    Was wondering if any of you can help me! following the guide on BalusC's blog [http://balusc.blogspot.com/2008/07/dao-tutorial-data-layer.html] for DAO and JSF and h:selectedItems, I have been able to come up with below code, but unfurtunately the page f:selectedItems will not populate the database resultSet.
    Can anyone spot the error? please help.
    DTO
    package mymodel;
    * This class represents a Data Transfer Object for the Service. This DTO can be used thoroughout all
    * layers, the data layer, the controller layer and the view layer.
    public class Service {
        // Properties ---------------------------------------------------------------------------------
        private String cname;
        private int telpack;
        private int analoq;
        private int port;
        private String publicip;
        private String location;
        private int officeno;
        // Constructors -------------------------------------------------------------------------------
         * Default constructor.
        public Service() {
            // Always keep the default constructor alive in a Javabean class.
        public Service(int officeno, String cname, String contact, int telpack, int analoq, int port, String publicip) {
            this.cname = cname;
            this.telpack = telpack;
            this.analoq = analoq;
            this.port = port;
            this.publicip = publicip;
            this.officeno = officeno;
        // Getters ------------------------------------------------------------------------------------
         * Returns the cname of this Service.
         * @return The cname of this Service.
        public String getcname() {
            return cname;
        public int getAnaloq() {
            return analoq;
        public int getTelpack() {
            return telpack;
        public int getPort() {
            return port;
        public String getLocation() {
            return location;
        public int getOfficeno() {
            return officeno;
        public String getCname() {
            return cname;
        // Setters ------------------------------------------------------------------------------------
         * Sets the cname of this Service.
         * @param cname The cname of this Service.
        public void setcname(String cname) {
            this.cname = cname;
        public String getPublicip() {
            return publicip;
        public void setAnaloq(int analoq) {
            this.analoq = analoq;
        public void setTelpack(int telpack) {
            this.telpack = telpack;
        public void setCname(String cname) {
            this.cname = cname;
        public void setPort(int port) {
            this.port = port;
        public void setPublicip(String publicip) {
            this.publicip = publicip;
        public void setLocation(String location) {
            this.location = location;
        public void setOfficeno(int officeno) {
            this.officeno = officeno;
        // Overrcnamee -----------------------------------------------------------------------------------
         * The Service cname is unique for each Service. So this should compare Services by cname only.
         * @see java.lang.Object#equals(java.lang.Object)
        public boolean equals(Object other) {
            return other instanceof Service && cname != null && cname.equals(((Service) other).cname);
         * The Service cname is unique for each Service. So Services with same cname should return same hashcode.
         * @see java.lang.Object#hashCode()
        public int hashCode() {
            return cname != null ? this.getClass().hashCode() + cname.hashCode() : super.hashCode();
    DAO
    package mydao;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import com.mvc.model.Service;
    import java.util.List;
    * This class represents a SQL Database Access Object for the {@link Service} DTO. This DAO should be
    * used as a central point for the mapping between the Service DTO and a SQL database.
    public class ServiceDAO {
        // Constants ----------------------------------------------------------------------------------
        private static final String SQL_SELECT_FROM_PACKAGE =
                "SELECT telinternet, analoq, dataport, publicip FROM package ORDER BY id";
        private static final String SQL_SELECT_LOCATION =
                "SELECT name FROM location";
        private static final String SQL_SELECT_OFFICE =
                "SELECT officeno FROM location";    // Vars ---------------------------------------------------------------------------------------
        private DAOFactory daoFactory;
        ArrayList<Integer> telinternet = new ArrayList<Integer>();
        ArrayList<Integer> analoq = new ArrayList<Integer>();
        ArrayList<Integer> dataport = new ArrayList<Integer>();
        ArrayList<Integer> publicip = new ArrayList<Integer>();
        ArrayList<Integer> location = new ArrayList<Integer>();
        ArrayList<Integer> office = new ArrayList<Integer>();
        // Constructors -------------------------------------------------------------------------------
        ServiceDAO(DAOFactory daoFactory) {
            this.daoFactory = daoFactory;
        // Actions ------------------------------------------------------------------------------------
        public List<Service> getLocation() throws DAOException {
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                connection = daoFactory.getConnection();
                preparedStatement = connection.prepareStatement(SQL_SELECT_LOCATION);
                resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    location.add(resultSet.getInt(1));
            } catch (SQLException e) {
                throw new DAOException(e);
            } finally {
                DAOUtil.close(resultSet);
                DAOUtil.close(preparedStatement);
                DAOUtil.close(connection);
            return null;
        //--Select all the colum from packages a
         * Hold the result in an ArrayList
         * @throws com.mvc.dao.DAOException
        public List<Service> getPackage() throws DAOException {
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                connection = daoFactory.getConnection();
                preparedStatement = connection.prepareStatement(SQL_SELECT_FROM_PACKAGE);
                resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    telinternet.add(resultSet.getInt(1));
                    analoq.add(resultSet.getInt(2));
                    dataport.add(resultSet.getInt(3));
                    publicip.add(resultSet.getInt(4));
            } catch (SQLException e) {
                throw new DAOException(e);
            } finally {
                DAOUtil.close(resultSet);
                DAOUtil.close(preparedStatement);
                DAOUtil.close(connection);
            return null;
        //--Select column name officeno from office table
         * Hold the result in an ArrayList
         * @throws com.mvc.dao.DAOException
        public List<Service> getOffice() throws DAOException {
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                connection = daoFactory.getConnection();
                preparedStatement = connection.prepareStatement(SQL_SELECT_OFFICE);
                resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    office.add(resultSet.getInt(1));
            } catch (SQLException e) {
                throw new DAOException(e);
            } finally {
                DAOUtil.close(resultSet);
                DAOUtil.close(preparedStatement);
                DAOUtil.close(connection);
            return null;
    Controller
    package mycontroller;
    import com.mvc.dao.DAOException;
    import com.mvc.dao.DAOFactory;
    import com.mvc.dao.ServiceDAO;
    import javax.faces.context.FacesContext;
    import java.util.*;
    import com.mvc.model.Service;
    import javax.faces.model.SelectItem;
    public class Controler {
        Service service = new Service();
        public static final ServiceDAO serviceDAO;
        private List<SelectItem> selectItems;
        private Service selectedItem;
        static {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            String databaseName = facesContext.getExternalContext().getInitParameter("database.name");
            serviceDAO = DAOFactory.getInstance(databaseName).getServiceDAO();
            try {
                fillSelectedItem();
            } catch (DAOException c) {
                c.printStackTrace();
        //--Actions
        public void doSend() {
            //doSend method
        //--Setters
        public void setSelectedItems(Service selectedItem) {
            this.selectedItem = selectedItem;
        //--Getters
        public List<SelectItem> getSelectItems() {
            return selectItems;
        //--Helpers--
        private void fillSelectedItem() throws DAOException {
            selectItems = new ArrayList<SelectItem>();
            for (Service serv : serviceDAO.getOffice()) {
                selectItems.add(new SelectItem(serv));
         * Returns the Service.
         * @return the Service.
        public Service getService() {
            return service;
    PAge
                  <h:form>
                    <h:selectOneMenu value="#{ServiceRequest.selectedItem}">
                        <f:selectItems value="#{ServiceRequest.selectItems}" />
                        <f:converter converterId="fooConverter" />
                    </h:selectOneMenu>
                    <h:commandButton value="submit" action="#{myBean.action}" />
                    <h:messages />
                </h:form>

  • Array List exceptions

    Hi,
    Want to know if ArrayList throws Index out of bound exception when we try to get element from an ArrayList thats empty.
    If This exception is not thrown, then whats the exception that is thrown in this scenario?
    Thanx

    By the time you'd logged on, written that question
    and waited for a response would it not have been
    quicker to write a noddy program to test this out?Or read the documentation? Quote:
    Throws:
    IndexOutOfBoundsException - if index is out of range (index < 0 || index >= size()).
    Unquote. When size() is 0, index is necessarily either < 0 or >= size().

Maybe you are looking for

  • Copy SMS from iphone 3g to iphone 4? is it possible

    Hi, any way to copy my SMS (Only SMS) from my 3g to my new iphone 4? i already have my contacts and Notes online, i still have many SMS that i need but at the same time, i don't want to restore from the 3g backup. my 3g was jailbroken/unlocked with a

  • Help Getting Simple ODCI program to work.

    Hello. I am trying to understand a pipelined table function / cartridge example given in the oracle docs: http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14289/dcitblfnxemp.htm#sthref859 But, I can't seem to get my example to work. I basical

  • Where should handling unit output determination procedure be assigned ?

    Hi In logistic execution, where should handling unit out put determination procedure be assigned pls ? Thanks In Advance

  • Time Capsule support for multiple XBoxes?

    I've read many posts about how to configure Airport Extreme and Time Capsule devices to support XBox Live, but they all focus on configuring network traffic to support a single XBox by forwarding ports to a static or reserved IP address for the XBox.

  • How to create internal links with pages...?

    I'm thinking of taking all my class notes with the computer and I wanted to know if Pages can create internal links (to other documents, or to another point in the same document). Or is there a better application to do this? iMac   Mac OS X (10.4.9)