0

edit: This is not a duplication. The other question linked is asking how to remove elements while iterating and not get the CME exception, in my question I don't want to iterate and remove elements at the same time. In fact I want to make sure that doesn't happen.

Im getting conccurrent modification error when trying to itterate through the vector theSpace, all my methods that affect it are synchronized so I dont understand whats causing the exception? (sorry for messy code new to java)

public class TupleSpace implements aTupleSpace {
  private Collection<aTuple> theSpace;

  public TupleSpace() {
    theSpace = new Vector<aTuple>();
  }

  public synchronized void out(aTuple v) {
    theSpace.add(v);
    notifyAll();
  }

  public synchronized void in(aTemplate t, aMonoVariable<aTuple> result) {
    while (true) {
      for (aTuple tup : theSpace) {
        if (t.matches(tup)) {
          result.becomes(tup);
          theSpace.remove(tup);
          return;
        }
        try {
          wait();
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block

          e.printStackTrace();
        }
      }
    }
  }

  public synchronized void rd(aTemplate t, aMonoVariable<aTuple> result) {
    while (true) {

      for (aTuple tup : theSpace) {
        if (t.matches(tup)) {
          result.becomes(tup);
          return;
        }
        try {
          wait();
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block

          e.printStackTrace();
        }
      }
    }
  }
}

==========code for .matches and .nth (helper)==========

public boolean matches(aTuple t) {

    if(this.elements.size() == t.length() ){
        for (int i=0; i<t.length(); i++) {
            if (!(this.nth(i).equals( t.nth(i)))){return false;}
        }
        return true;
    }return false;
}
public TypedValue nth(int n) {
if( n < 0 || n >= elements.size()) return null;
else return elements.get(n);
R-4
  • 75
  • 4
  • you can't add and remove from a collection at the same time. A workaround is to use `new Vector(theSpace);` in the enhanced for. – Rahul Sharma Mar 08 '16 at 17:23
  • 1
    If you modify a list while iterating over it you get an CME even if you have just one thread and one loop. – Peter Lawrey Mar 08 '16 at 17:26
  • Are you sure that `matches` doesn't call back here. – Peter Lawrey Mar 08 '16 at 17:28
  • I understand the CME is caused by modifying while incinerating, but I can't see how would happen in my code. I'll add code for .matches to the original, but I don't think that's what's causing it – R-4 Mar 08 '16 at 17:39

0 Answers0