Java中平時用的最多的map就是hashmap但是它卻是線程不安全的。
那除了hashmap還有哪些常見的線程安全的map?
1.hashtable
Map<String,Object> hashtable=new Hashtable<String,Object>();
這是所有人最先想到的,那爲什麼它是線程安全的?那就看看它的源碼,我們可以看出我們常用的put,get,containsKey等方法都是同步的,所以它是線程安全的
public synchronized boolean containsKey(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return true;
}
}
return false;
}
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
2.synchronizedMap:
Map<String,Object> synchronizedMap= Collections.synchronizedMap(new Hashtable<String,Object>());
它其實就是加了一個對象鎖,每次操作hashmap都需要先獲取這個對象鎖,這個對象鎖有加了synchronized修飾,鎖性能跟hashtable差不多。
SynchronizedMap(Map<K,V> m, Object mutex) {
this.m = m;
this.mutex = mutex;
}
public int size() {
synchronized (mutex) {return m.size();}
}
public boolean isEmpty() {
synchronized (mutex) {return m.isEmpty();}
}
public boolean containsKey(Object key) {
synchronized (mutex) {return m.containsKey(key);}
}
public boolean containsValue(Object value) {
synchronized (mutex) {return m.containsValue(value);}
}
public V get(Object key) {
synchronized (mutex) {return m.get(key);}
}
3、ConcurrentHashMap
Map<String,Object> concurrentHashMap=new ConcurrentHashMap<String,Object>();
這個是目前使用最多,而且也是最推薦的一個集合,實現也是比較複雜的一個。我們看源碼其實是可以發現裏面的線程安全是通過cas+synchronized+volatile來實現的,其中也可看出它的鎖是分段鎖,所以它的性能相對來說是比較好的。整體實現還是比較複雜的