Thread safety when iterating through an ArrayList using foreach

后端 未结 4 1716
既然无缘
既然无缘 2021-01-02 09:25

I\'ve got an ArrayList which is being instantiated and populated on the background thread (I use it to store the Cursor data). At the same time it

4条回答
  •  借酒劲吻你
    2021-01-02 10:04

    You could use a Vector which is the thread-safe equivalent of ArrayList.

    EDIT: Thanks to Fildor's comment, I now know this doesn't avoid ConcurrentModificationException from being thrown using multiple threads:

    Only single calls will be synchronized. So one add cannot be called while another thread is calling add, for example. But altering the list will cause the CME be thrown while iterating on another thread. You can read the docs of iterator on that topic.

    Also interesting:

    • Why is Java Vector class considered obsolete or deprecated?
    • Vector vs Collections.synchronizedList(ArrayList)

    Long story short: DO NOT use Vector.

提交回复
热议问题