我有一个静态的hashMap,被多个线程共享。我不会遍历这个map,只是使用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);
}
}
}
}