Why do I need to synchronize a list returned by Collections.synchronizedList

前端 未结 2 369
傲寒
傲寒 2020-12-03 02:52

i found this at dos.oracle.com

public static List synchronizedList(List list)

Returns a synchronized (thread-safe) list backed by the spe

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 03:42

    The list being synchronized only means that add, remove etc. operations are synchronized and therefore atomic. Iteration however is not and if a thread adds while another is iterating, you could get a ConcurrentModificationException.

    By manually synchronizing your iteration block, you ensure that the list is not modified while iterating.

    One alternative is to use a CopyOnWriteArrayList which provides an iterator that iterates over the list as it was known when the iteration started, regardless of subsequent modifications. That collection is however not very efficient if you need to change the content of the list very often.

提交回复
热议问题