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

后端 未结 9 1900
星月不相逢
星月不相逢 2020-11-28 05:28

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

My theory is that when add is called concurrently by two threads,

9条回答
  •  一向
    一向 (楼主)
    2020-11-28 06:08

    The behavior is probably undefined since ArrayList isn't threadsafe. If you modify the list while an Iterator is interating over it then you will get a ConcurrentModificationException. You can wrap the ArrayList with Collection.synchronizedList or use a thread-safe collection (there are many), or just put the add calls in a synchronized block.

提交回复
热议问题