问题描述
我有一个静态hashMap,与多个线程共享.我根本没有迭代地图,而是只使用了get
,put
,remove
.从ConcurrentModificationException
安全吗?
I have a static hashMap, shared with multiple threads. I am not iterating the map at all but just uses the get
, put
, remove
. Is it safe from 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);
}
}
}
}
推荐答案
从ConcurrentModificationException
开始是安全的.该异常仅由使用常规迭代器或分隔器对地图或其视图之一进行迭代(在某种意义上)的方法引发.
It is safe from ConcurrentModificationException
. That exception is only thrown by methods that iterate (in some sense) the map or one of its views using a conventional iterator or a spliterator.
但是,由于HashMap
不是线程安全的类,因此如果您在没有适当的外部外部同步的情况下从多个线程中使用它,则可能会发生不良情况.其中包括(以增加不良程度为顺序)
However, since HashMap
is not a thread-safe class, if you use it from multiple threads without proper external external synchronization, bad things can happen. These include (in order of increasing badness)
-
size()
方法报告错误的值. - 条目神秘地消失,暂时或永久消失.
- 可能的NPE和其他未经检查的异常.
- 可能的无限循环是由于多个线程在哈希链中创建循环而造成的不幸的操作序列.
- The
size()
method reporting the wrong value. - Entries mysteriously disappearing, either temporarily or permanently.
- Possible NPEs and other unchecked exceptions.
- Possible infinite loops due to an unfortunate sequence of operations by multiple threads creating a loop in a hash chain.
您的示例代码不安全 ... ...但是您不会遇到快速失败" ConcurrentModificationException
.取而代之的是,您可能会在随机"时间遇到难以重现的无法解释的错误.
Your example code is unsafe ... but you won't get a "fast fail" ConcurrentModificationException
. Instead you are likely to get inexplicable errors at "random" times that are difficult to reproduce.
这篇关于可以拿放在没有迭代的情况下删除HashMap中的elemetn导致ConcurrentModificationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!