Concurrent threads adding to ArrayList at same time - what happens?

Marcus Leon picture Marcus Leon · Apr 26, 2010 · Viewed 79.5k times · Source

We have multiple threads calling add(obj) on an ArrayList.

My theory is that when add is called concurrently by two threads, that only one of the two objects being added is really added to the ArrayList. Is this plausable?

If so, how do you get around this? Use a synchronized collection like Vector?

Answer

derivation picture derivation · Apr 26, 2010

There is no guaranteed behavior for what happens when add is called concurrently by two threads on ArrayList. However, it has been my experience that both objects have been added fine. Most of the thread safety issues related to lists deal with iteration while adding/removing. Despite this, I strongly recommend against using vanilla ArrayList with multiple threads and concurrent access.

Vector used to be the standard for concurrent lists, but now the standard is to use the Collections synchronized list.

Also I highly recommend Java Concurrency in Practice by Goetz et al if you're going to be spending any time working with threads in Java. The book covers this issue in much better detail.