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

后端 未结 9 1897
星月不相逢
星月不相逢 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:12

    Any number of things could happen. You could get both objects added correctly. You could get only one of the objects added. You could get an ArrayIndexOutOfBounds exception because the size of the underlying array was not adjusted properly. Or other things may happen. Suffice it to say that you cannot rely on any behavior occurring.

    As alternatives, you could use Vector, you could use Collections.synchronizedList, you could use CopyOnWriteArrayList, or you could use a separate lock. It all depends on what else you are doing and what kind of control you have over access to the collection.

提交回复
热议问题