title: Synchronizing elements in an array
body: <p>I am new to multi-threading in Java and don't quite understand what's going on.</p>
  
  <p>From online tutorials and lecture notes, I know that the <code>synchronized</code> block, which must be applied to a non-null object, ensures that only one thread can execute that block of code. Since an array is an object in Java, synchronize can be applied to it. Further, if the array stores objects, I should be able to synchronize each element of the array too.</p>
  
  <p>My program has several threads updated an array of numbers, hence I created an array of <code>Long</code> objects:</p>
  
  <pre><code>synchronized (grid[arrayIndex]){
      grid[arrayIndex] += a.getNumber();
  }
  </code></pre>
  
  <p>This code sits inside the <code>run()</code> method of the thread class which I have extended. The array, grid, is shared by all of my threads. However, this does not return the correct results while running the same program on one thread does.</p>