I am trying to make a simulation of a program which simulates different threads removing and adding objects in an ArrayList. However, late in the simulation I get concurrentModificationExceptions (when the threads are trying to access and modify the same variable while an iterator is being used to iterate through the data). I have searched it up and seen some topics about this saying that I needed to use locks/synchronization and/or using ListIterators instead of enhanced for-loops, however, none of these options seemed to fix the problem. Here is what I have tried to do so far:
public Object removeSomething1(){
synchronized(this){ //Also tried only putting it around the remove block
for(Object o : myList){
myList.remove(o);
return o;
}
}
}
//This is another variaton which did not yield any improved result
public Object removeSomething2(){
ListIterator<Object> iter = myList.listIterator();
While(iter.hasNext()){
Object s = iter.next();
synchronized(this){
iter.remove();
}
return s;
}
}
//After some request here is also the simple code which adds to the list
public addSomething(Object o){
myList.add(o);
}
I execute 5 threads which calls upon these methods in their run() method in an interval of 500ms (using Thread.sleep()). If I increase the sleep timer in each thread and put a Thread.sleep() between each instanciation of threads, the problem seems to go away, but I want the threads to run at (closely) the same time without them interfering with the iterator at the same time which envokes the ConcurrentModificationException.