多线程HashMap的读取是否需要同步?

多线程HashMap的读取是否需要同步?这个问题一直困扰着我,虽然Collections提供了同步的map,但我一般都是直接使用HashMap,读的时候不同步,写的时候才同步。下面是我从HashMap里截取的读的源代码,估计读的时候应该是不用同步的。其他的Map我没有仔细看,但估计应该也是差不多。

[code] 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);
}
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值