I am using an Array List to store data about moving objects on screen. I suspect this is because my renderer and my logic are running on separate threads, but sometimes when data is removed from the list I get an indexOutOfBoundsException. I have taken all the steps I can think of to avoid this including try/catch but the exception still sometimes occurs. This is the part of my renderer thread that seems to cause the exception.
public void drawMobs(GL10 gl) {
boolean playing = MyLaunchActivity.getPlaying();
if(playing == true){
try{
ArrayList<String> mobDat = Play.getMobDat();
while (currentLoadSpace < mobDat.size()){
if(!mobDat.isEmpty() || currentLoadSpace < mobDat.size()){
loadObject = mobDat.get(currentLoadSpace);
float loadCoordX = Float.parseFloat(mobDat.get(currentLoadSpace + 2));
float loadCoordY = Float.parseFloat(mobDat.get(currentLoadSpace + 3));
/*some rendering*/
currentLoadSpace+=4;
}
}
}catch( ArrayIndexOutOfBoundsException e){ Log.d(TAG, "caught");}
currentLoadSpace = 0;
}}
as you can see I have tried a few things but the error still occurs. Here is the error log
01-02 14:02:42.650: E/AndroidRuntime(6947): FATAL EXCEPTION: GLThread 10
01-02 14:02:42.650: E/AndroidRuntime(6947): java.lang.IndexOutOfBoundsException: Invalid index 23, size is 20
01-02 14:02:42.650: E/AndroidRuntime(6947): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
01-02 14:02:42.650: E/AndroidRuntime(6947): at java.util.ArrayList.get(ArrayList.java:308)
01-02 14:02:42.650: E/AndroidRuntime(6947): at basicmelon.games.agameofsorts.LoadLevel.drawMobs(LoadLevel.java:530)
01-02 14:02:42.650: E/AndroidRuntime(6947): at basicmelon.games.agameofsorts.MyGLSurfaceRenderer.onDrawFrame(MyGLSurfaceRenderer.java:82)
01-02 14:02:42.650: E/AndroidRuntime(6947): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1429)
01-02 14:02:42.650: E/AndroidRuntime(6947): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1184)
One possible solution could be:
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html
If this is not an option, you could use synchronized(yourList) {} to prevent concurent modifications.