Thread-safe iteration over a collection

后端 未结 8 1225
情歌与酒
情歌与酒 2020-12-05 05:21

We all know when using Collections.synchronizedXXX (e.g. synchronizedSet()) we get a synchronized \"view\" of the underlying collection.

Ho

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 05:51

    It does depend on the result one needs to achieve cloning/copying/toArray(), new ArrayList(..) and the likes obtain a snapshot and does not lock the the collection. Using synchronized(collection) and iteration through ensure by the end of the iteration would be no modification, i.e. effectively locking it.

    side note:(toArray() is usually preferred with some exceptions when internally it needs to create a temporary ArrayList). Also please note, anything but toArray() should be wrapped in synchronized(collection) as well, provided using Collections.synchronizedXXX.

提交回复
热议问题