【问题标题】:How to explain duplicate entries in Java Hashmap?如何解释 Java Hashmap 中的重复条目?
【发布时间】:2016-07-29 10:43:09
【问题描述】:
  1. 这是在多线程下
  2. 我已阅读有关 HashMap 的主题,但找不到相关问题/答案

代码:

 private Map<String, String> eventsForThisCategory;
    ...
    Map<String, String> getEventsForThisCategory() {
        if (eventsForThisCategory == null) {
            Collection<INotificationEventsObj> notificationEvents = notificationEventsIndex.getCategoryNotificationEvents(getCategoryId());
            eventsForThisCategory = new HashMap<String, String>();
            for(INotificationEventsObj notificationEvent : notificationEvents) {
                eventsForThisCategory.put(notificationEvent.getNotificationEventID(), notificationEvent.getNotificationEventName());
            }
            logger.debug("eventsForThisCategory is {}", eventsForThisCategory);
        }
        return eventsForThisCategory;
    }

输出:

app_debug.9.log.gz:07 Apr 2016 13:47:06,661 DEBUG [WirePushNotificationSyncHandler::WirePushNotification.Worker-1] - eventsForThisCategory 是 {FX_WIRE_DATA=关键经济数据, ALL_FX_WIRE=All, ALL_FX_WIRE=All, FX_WIRE_HEADLINES=重要标题}

这怎么可能?

【问题讨论】:

  • 嗯,这是不可能的。至少不是HashMap&lt;String, String&gt;。你的代码有什么样的并发性?两个 ALL_FX_WIRE 键之间是否存在不同的空格?
  • @Kayaman 是多线程的。没有空格可以区分这两个键。如您所见,它打印出地图,我不相信它会自动修剪字符串
  • @YuriBlanc 我会更新问题,我已经阅读了该主题,对 HashMap 的工作原理有基本的了解,甚至知道 HashMap 不是线程安全的。
  • 嗯,唯一想到的是并发问题。我假设您无法可靠地复制该行为?

标签: java hashmap duplicates multiple-entries


【解决方案1】:

HashMap 不是多线程中的线程安全。 你可以尝试使用Collections.synchronizedMap() 来包装你的 hashMap 实例 或者使用ConcurrentHashMap 可能更好

【讨论】:

  • 不是我期待的答案。你没有解释它是如何发生的。
【解决方案2】:

我很确定您的地图不会同时有两个相等的键。您看到的是在迭代地图时修改地图的效果(在toString() 中)。当第二个“ALL_FX_WIRE”被写入时,第一个将不再出现在地图中。

你已经知道HashMap 不是线程安全的。另外,eventsForThisCategory 可以在 eventsForThisCategory.toString() 运行时被另一个线程修改。所以这是意料之中的。

确保eventsForThisCategory未被多个线程同时修改(或切换到ConcurrentHashMap),并确保toString()运行时未被修改(创建调试输出时调用它)。

【讨论】:

  • 啊,对了,我完全忘记了toString 也是对 Map 的迭代。感谢您的回答,
猜你喜欢
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-21
  • 2011-05-04
  • 1970-01-01
相关资源
最近更新 更多