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