问题再现:并发下对Map进行add和遍历输出,出现java.util.ConcurrentModificationException异常
public class MapTest {
public static void main(String[] args) {
Map<String,String> map=new HashMap<>();
for (int i = 0; i < 30; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}
原因:HashMap在并发下线程不安全
解决方式一:
使用Collections.synchronizedMap()
Map<String,String> map= Collections.synchronizedMap(new HashMap<>());
public class MapTest {
public static void main(String[] args) {
//Map<String,String> map=new HashMap<>();
Map<String,String> map= Collections.synchronizedMap(new HashMap<>());
for (int i = 0; i < 30; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}
说明:
查看synchronizedMap(),发现该方法返回SynchronizedMap<>(m)
解决方式二:
使用ConcurrentHashMap创建map
Map<String,String> map=new ConcurrentHashMap<>();
public class MapTest {
public static void main(String[] args) {
//Map<String,String> map=new HashMap<>();
//Map<String,String> map= Collections.synchronizedMap(new HashMap<>());
Map<String,String> map=new ConcurrentHashMap<>();
for (int i = 0; i < 30; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}
说明:
查看ConcurrentHashMap源码发现,该创建方法最后调用putAll(m)方法
putAll方法中的for循环调用putVal方法
putVal方法源码:
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
我们发现这个putVal方法将Node<K,V>这个对象放在代码块中用synchronized修饰!