阻塞或非阻塞 - 在 Java 中的 HashMap 中重新散列期间添加元素

Blocking Or NonBlocking - Adding Element during Rehashing in HashMap in Java

如 HashMap 文档中所述,当 HashMap 已满 75% 时,HashMap 在内部执行所有现有对象的重新散列。

如果在执行重新散列时,添加了任何元素 ->

HashMap 如何处理在进行重新散列时添加新元素?

来自Javadoc

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

您必须应用外部同步;否则,面对多个线程的访问,地图的状态可能会被破坏。

如果您正在同步,则在地图重新排列自身时不能添加其他元素。

如果您没有进行同步,那么您没有按照记录使用 class,因此行为未定义。

它不是阻塞的,但它也不会“允许在重新散列过程之间添加元素”。java.util.HashMap 被记录为线程不安全。如果您尝试在地图上添加或删除它重新散列,你会得到不一致的行为。

您可能要考虑使用 java.util.concurrent.ConcurrentHashMap