Thread-safe iteration over a collection

后端 未结 8 1228
情歌与酒
情歌与酒 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:45

    You've already answered your bonus question really: no, using an enhanced for loop isn't safe - because it uses an iterator.

    As for which is the most appropriate approach - it really depends on how your context:

    • Are writes very infrequent? If so, CopyOnWriteArrayList may be most appropriate.
    • Is the collection reasonably small, and the iteration quick? (i.e. you're not doing much work in the loop) If so, synchronizing may well be fine - especially if this doesn't happen too often (i.e. you won't have much contention for the collection).
    • If you're doing a lot of work and don't want to block other threads working at the same time, the hit of cloning the collection may well be acceptable.

提交回复
热议问题