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

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

    You could also get a null, an ArrayOutOfBoundsException, or something left up to the implementation. HashMaps have been observed to go into an infinite loop in production systems. You don't really need to know what might go wrong, just don't do it.

    You could use Vector, but it tends to work out the interface is not rich enough. You will probably find that you want a different data structure in most cases.

    0 讨论(0)
  • 2020-11-28 06:32

    java.util.concurrent has a thread-safe array list. The standard ArrayList is not thread-safe and the behavior when multiple threads update at the same time is undefined. There can also be odd behaviors with multiple readers when one or more threads is writing at the same time.

    0 讨论(0)
  • 2020-11-28 06:33

    You could use instead of ArrayList(); :

    Collections.synchronizedList( new ArrayList() );
    

    or

    new Vector();
    

    synchronizedList as of me preferable because it's:

    • faster on 50-100%
    • can work with already existing ArrayList's
    0 讨论(0)
提交回复
热议问题