I have two seperate threads:
- logicThread – for ai, movement, sprite sorting and destruction of sprites
- drawingThread – for drawing (canvas.draw())
My logic thread calls ArrayList.remove(), so I would think when the drawing thread comes to draw there could be a chance of crashing because the index no longer exists.
code sample:
drawingThread extends Thread {
logicThread = new LogicThread;
logicThread.start();
public void run(){
while(running) {
for(int i=0; i<npc.size(); i++){
npc.get(i).callDraw();
}
}
// stop logicThread when out of gameloop
logicThread.running = false;
}}
LogicThread extends Thread {
public void run(){
while(running){
for(int i=0; i<npc.size();i++){
if(npc.get(i).isDead()){
npc.remove(i);
}
npc.trimToSize();
}
Collection.sort(npc);
}
}}
Which would be the correct way to prevent an exception, syncronized or trycatch?
Also are there any benefits from using one over the other?
synchronized(logicThread) {
for(int i=0; npc.size(); i++) {
npc.callDraw();
}}
or
try {
npc.callDraw();
} catch(Exception e) {}
Just for note: use iterators to remove items from collection:
Catching IndexOutOfBound exception is valid if it’s acceptable. Another way – is to create array copy in drawing thread, which will guarantee that you don’t get IndexOutOfBound. You can just add a check isDead() inside drawing loop