Need Fool Proof Synchronization of ArrayList in A Multi-threaded Environment

前端 未结 4 905
闹比i
闹比i 2021-02-15 15:33

I\'ve been at this for a week now doing my research on how to properly synchronize an ArrayList.

My main issue in a nutshell is I have a \"master\" ArrayList of objects.

4条回答
  •  旧巷少年郎
    2021-02-15 16:19

    If you're modifying during an iteration, yeah, you have to use option 3. None of the others will actually do what you want.

    More specifically: given what you want to do, you have to lock the entire list for the length of the iteration, because you might modify it in the middle, which would corrupt any other iterators working on the list at the same time. That means option 3, since the Java language can't just have a "synchronized iterator" -- the iterator itself can only synchronize individual calls to hasNext() or next(), but it can't synchronize across the entire length of the iteration.

提交回复
热议问题