CopyOnWriteArrayList vs ArrayList and ConcurrentModificationException

public class ArrayAccess {
  final static List ints = new ArrayList();
  static {
    ints.add(1);
    ints.add(2);
    ints.add(3);
  }

  public static void main(String[] args) {
    iteratingThread().start();
    ints.remove(2);
    for (Integer j : ints) {
      System.err.println(threadName() + j);
    }
  }

  private static Thread iteratingThread() {
    return new Thread(new Runnable() {

      @Override
      public void run() {
        for (Integer i : ints) {
          System.out.println(threadName() + i);
          sleepSeconds(1);
        }
      }
    });
  }

  private static void sleepSeconds(int n) {
    try {
      Thread.sleep(1000 * n);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  private static String threadName() {
    return currentThread().getName() + ":";
  }
}

Result:
Thread-0:1
main:1
main:2
Exception in thread "Thread-0" java.util.ConcurrentModificationException
...

While one thread was slowly iterating through the list, another thread was trying to remove an item and we got concurrent modification exception. The solution is to use CopyOnWriteArrayList:

final static List ints = new CopyOnWriteArrayList();

Then the result is:
Thread-0:1
main:1
main:2
Thread-0:2
Thread-0:3

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s