I am making a game on android which will have three threads. These will be my GL rendering thread, my game update thread and the UI thread.
The game revolves around an ArrayList (and also a regular array) of ‘ball’ objects. The user creates a ball by tapping the screen, the game update thread moves the balls around the screen and the rendering thread draws all the balls.
The problem I’m having is dealing with the concurrency issue that arises from many threads accessing the same data, namely the array of balls. An issue in particular is receiving an out of bounds exception when the game thread removes a ball, and the rendering thread tries to access the removed ball.
If you consider the code samples I’ve posted. What is the best way to ensure that once either of these code blocks (on different threads) has started execution, that the other cannot start until it has finished?
rendering thread
int size = balls.size();
for(int i = 0; i < size; i++){
Ball ball = balls.get(i);
drawBall(ball.xCoord, ball.yCoord, ball.image);
}
Game thead
int size = balls.size();
for(int i = size -1; i >= 0; i--){
Ball b = balls.get(i);
b.updateBallPosition();
b.updateBallVelocity();
if(b.isOutOfBounds())
balls.remove(i);
}
Use a
synchronizedblock to ensure mutual exclusion on a portion of code:Rendering thread:
Game thread:
At this point, only one of the two threads can execute the code, while the other will block. Note that they must both be synchronized on the same lock object.