I'm doing an app for Android , and part of my code is like the following:
public void loop(){
for(Car car:carList)
car.run();
}
The bad thing is that I get the error java.util.ConcurrentModificationException
. I was researching, I used iterators and the java notation synchronized , because as I read in the Oracle documentation, the error can be generated by several threads using my "loop" method.
public synchronized void loop(){
Iterator<Car> carIterator = carList.iterator();
while(cardIterator.hasNext()){
carIterator.next().run();
}
}
I really do not know what else can solve this problem. I use the class of this method and this one, above all, in background services and activities , I also use them (using the singleton pattern to instantiate).
Thanks guys for the support! Well, to give more details of my problem, the carList is an ArrayList with Car objects My class car is this:
public class Car{
private int mSpeed;
private int mDistance; //inicializo con cero
........
public void run(){
mSpeed=getRandomSpeed();
mDistance+=mSpeed;
updateDistanceInDB();//Aquí lo guardo en una base de dato sqlite
}
.........
}
-The error tells me that this was generated on the line where I execute the run () method inside the loop. Also, what is strange is that this error does not happen in another cell phone that I have. -This is the page of the official documentation of oracle that tells me that the error may be due to several threads using my list, so use synchronized but it did not solve
Why on other phones will work and others will not? Thanks guys for your help!