1
  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=Key Economic Data, ALL_FX_WIRE=All, ALL_FX_WIRE=All, FX_WIRE_HEADLINES=Critical Headlines}

这怎么可能?

4

2 回答 2

1

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

您已经知道这HashMap不是线程安全的。PluseventsForThisCategory可以在eventsForThisCategory.toString()运行时被另一个线程修改。所以这是可以预料的。

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

于 2016-04-08T08:59:47.043 回答
0

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

于 2016-04-08T08:50:39.497 回答