hashMap虽然效率好,但是多线程下是不安全的。一般在多线程的场景,有几种不同的方式去代替:
- Collections.synchronizedMap(Map)创建线程安全的map集合
- Hashtable
- ConcurrentHashMap:性能和效率好
详细解析
Collections.synchronizedMap(Map)
private static class SynchronizedMap<K,V> implements Map<K,V>, Serializable {
private final Map<K,V> m; // Backing Map
final Object mutex; // Object on which to synchronize
SynchronizedMap(Map<K,V> m) {
this.m = Objects.requireNonNull(m);
mutex = this;
}
SynchronizedMap(Map<K,V> m, Object mutex) {
this.m = m;
this.mutex = mutex;
}
public V put(K key, V value) {
synchronized (mutex) {
return m.put(key, value);}
}
public V remove(Object key) {
synchronized (mutex) {
return m.remove(key);}
}
...
HashTable
线程安全,但是效率低,因为是synchronized方法。
public Hashtable(