title: Thread safe remove/add element from one list to another
body: <p>Let's say I have two lists: <code>fooList</code>, and <code>barList</code>. Also, let's say I have two threads: first one iterates over fooList and if certain criteria is met (condition is true) it removes element from fooList and adds it to barList. Second one iterates over barList, and if some other condition is true it removes element from barList, and adds it to fooList.</p>
  
  <p>The way I handled it is:</p>
  
  <pre><code>private static Object sharedLock = new Object();
  
  Thread t1 = new Thread() {
      public void run() {
          synchronized (sharedLock) {
  
              for (Iterator&lt;String&gt; iterator = fooList.iterator(); iterator.hasNext();) {
                  String fooElement = iterator.next();
                  if (condition == true) {
  
                      iterator.remove();
                      barList.add(fooElement);
  
                  }
              }
  
          }
      }
  };
  
  Thread t2 = new Thread() {
      public void run() {
          synchronized (sharedLock) {
  
              for (Iterator&lt;String&gt; iterator = barList.iterator(); iterator.hasNext();) {
                  String barElement = iterator.next();
                  if (otherCondition == true) {
  
                      iterator.remove();
                      fooList.add(barElement);
  
                  }
              }
  
          }
      }
  };
  </code></pre>
  
  <p>What I want to know is have I handled it properly? Is there a race condition possibility? Is there a better way to achieve the same functionality?</p>
  
  <p><strong>EDIT</strong> Looks like proper way of implementing this is:</p>
  
  <pre><code>Thread t1 = new Thread() {
      public void run() {
  
          for (String fooElement : fooList) {
              if (condition == true) {
  
                  fooList.remove(fooElement);
                  barList.add(fooElement);
  
              }
          }
  
      }
  };
  
  Thread t2 = new Thread() {
      public void run() {
  
          for (String barElement : barList) {
              if (otherCondition == true) {
  
                  barList.remove(barElement);
                  fooList.add(barElement);
  
              }
          }
  
      }
  };
  </code></pre>
  
  <p>where both: <code>fooList</code> and <code>barList</code> are of type <code>CopyOnWriteArrayList&lt;String&gt;</code></p>