Here is some pseudo code as follows.
public class MyObject
{
private List<Object> someStuff;
private Timer timer;
public MyObject()
{
someStuff = new ArrayList<Object>();
timer = new Timer(new TimerTask(){
public void run()
{
for(Object o : someStuff)
{
//do some more stuff involving add and removes possibly
}
}
}, 0, 60*1000);
}
public List<Object> getSomeStuff()
{
return this.someStuff;
}
}
So essentially the problem is that other objects not listed in the code above call getSomeStuff() to get the list for read-only purposes. I am getting concurrentmodificationexception in the timer thread when this occurs. I tried making the getSomeStuff method synchronized, and even tried synchronized blocks in the timer thread, but still kept getting the error. What is the easiest method of stopping concurrent access of the list?
You can use either
java.util.concurrent.CopyOnWriteArrayListor make a copy (or get an array withCollection.toArraymethod) before iterating the list in the thread.Besides that, removing in a for-each construction breaks iterator, so it’s not a valid way to process the list in this case.
But you can do the following:
or
Also note, that if your code accesses the list from different threads and the list is modified, you need to synchronize it. For example:
But note, that operations withing locks should be as short as possible.