我有一个静态 hashMap,与多个线程共享。我根本没有迭代地图,而只是使用get, put, remove。安全ConcurrentModificationException吗?该方法看起来像这样private static Map<Long, Integer> TRACKER = new HashMap<Long,Integer>();public static void track(Long tid, boolean b) { if (b) { if (TRACKER.containsKey(tid)) { TRACKER.put(tid, TRACKER.get(tid) + 1); } else { TRACKER.put(tid, 1); } } else { Integer n = TRACKER.get(tid); if (n != null) { n = n -1; if (n == 0) { TRACKER.remove(tid); } else { TRACKER.put(tid, n); } } } }
2 回答
噜噜哒
TA贡献1784条经验 获得超7个赞
安全
ConcurrentModificationException
吗?
它是安全的ConcurrentModificationException
。该异常仅由使用传统迭代器或拆分器迭代(在某种意义上)地图或其视图之一的方法抛出。
但是,由于HashMap
它不是线程安全的类,如果在没有适当外部外部同步的情况下从多个线程使用它,可能会发生不好的事情。这些包括(按不良程度增加的顺序)
size()
报告错误值的方法。条目神秘地暂时或永久消失。
可能的 NPE 和其他未经检查的异常。
由于多个线程在哈希链中创建循环的不幸操作序列,可能导致无限循环。
您的示例代码不安全……但您不会得到“快速失败” ConcurrentModificationException
。相反,您可能会在难以重现的“随机”时间出现莫名其妙的错误。
添加回答
举报
0/150
提交
取消