title: serialization of code blocks between different threads
body: <p>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.</p>
  
  <p>The game revolves around an <code>ArrayList</code> (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.</p>
  
  <p>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 <code>out of bounds exception</code> when the game thread removes a ball, and the rendering thread tries to access the removed ball.</p>
  
  <p>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?</p>
  
  <p><strong>rendering thread</strong></p>
  
  <pre><code>int size = balls.size();
  for(int i = 0; i &lt; size; i++){
        Ball ball = balls.get(i);
        drawBall(ball.xCoord, ball.yCoord, ball.image);
  }
  </code></pre>
  
  <p><strong>Game thead</strong></p>
  
  <pre><code>int size = balls.size();
  for(int i = size -1; i &gt;= 0; i--){
      Ball b = balls.get(i);
      b.updateBallPosition();
      b.updateBallVelocity();
  
      if(b.isOutOfBounds())
          balls.remove(i);
  }
  </code></pre>