浏览 1385 次
|
锁定老贴子 主题:多线程HashMap的读取是否需要同步?
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
|---|---|
| 作者 | 正文 |
|
时间:2007-07-20 关键字: 多线程同步
多线程HashMap的读取是否需要同步?这个问题一直困扰着我,虽然Collections提供了同步的map,但我一般都是直接使用HashMap,读的时候不同步,写的时候才同步。下面是我从HashMap里截取的读的源代码,估计读的时候应该是不用同步的。其他的Map我没有仔细看,但估计应该也是差不多。
public Object get(Object key) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry e = table[i];
while (true) {
if (e == null)
return e;
if (e.hash == hash && eq(k, e.key))
return e.value;
e = e.next;
}
}
public boolean containsKey(Object key) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry e = table[i];
while (e != null) {
if (e.hash == hash && eq(k, e.key))
return true;
e = e.next;
}
return false;
}
static Object maskNull(Object key) {
return (key == null ? NULL_KEY : key);
}
static int hash(Object x) {
int h = x.hashCode();
h += ~(h << 9);
h ^= (h >>> 14);
h += (h << 4);
h ^= (h >>> 10);
return h;
}
static int indexFor(int h, int length) {
return h & (length-1);
}
static boolean eq(Object x, Object y) {
return x == y || x.equals(y);
}
声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
|
| 返回顶楼 | |
|
时间:2007-07-20
HashMap是不提供同步机制的。
建议使用ConcurrentHashMap |
|
| 返回顶楼 | |
|
时间:2007-07-20
读取不需要同步,但是写可要同步了!之所以HashMap常用,因为它不支持同步,因此读的效率高了
|
|
| 返回顶楼 | |




