ConcurrentHashMap 的 forEach 方法是线程安全的吗?

Is ConcurrentHashMap's forEach method thread-safe?

如果要遍历 ConcurrentHashMap 中的所有元素,是否使用线程安全的forEach方法?

这取决于你所说的线程安全是什么意思。

  • 如果您在 forEach 调用期间允许其他线程修改地图,那么是的,它是线程安全的。
  • 如果您希望地图在 forEach 进行期间不可修改,以便其他线程在尝试修改它时被阻塞或出错,那么不,它不是。

API documentation 说:

However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access.

...

Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException.... Bear in mind that the results of aggregate status methods ... are typically useful only when a map is not undergoing concurrent updates in other threads. Otherwise the results of these methods reflect transient states that may be adequate for monitoring or estimation purposes, but not for program control.