title: Implement a thread-safe ArrayList in Java by locking
body: <p>I want to write a simple thread-safe arraylist which supports:</p>
  
  <p>add(), remove(int i), insert(int i), update(int i), and get(int i)</p>
  
  <p>One simple implementation is to add lock to the internal data structure(an object array for example), but it is not good enough because only one thread could access the list at a time.</p>
  
  <p>Therefore my initial plan is to add lock to each data slot so that different threads could have access to elements in different indexes at the same time. The data structure will look like this:</p>
  
  <pre><code>class MyArrayList {
      Lock listlock;
      Lock[] locks;
      Object[] array;
  }
  </code></pre>
  
  <p>The locking should work as follows if there is no need to do resize():</p>
  
  <ul>
  <li>for get(int i), a thread needs to acquire locks[i].</li>
  <li>for insert(int i), a thread needs to acquire all locks[j] for j >= i, and listlock.</li>
  <li>for remove(int i), a thread needs to acquire all locks[j] for j >= i, and listlock.</li>
  <li>for add(), a thread needs to acquire listlock.</li>
  <li>for insert(), a thread needs to acquire locks[i].</li>
  </ul>
  
  <p>My questions are:</p>
  
  <ul>
  <li>How to handle the locks when resizing while more objects are adding and I need to create a new larger array to hold all objects. It is annoying because some other threads may also wait for the locks to be released, </li>
  <li>Any better suggestions to implement such thread-safe arraylist?</li>
  </ul>