2007-07-20

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

关键字: 多线程同步
多线程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);
    }
评论
ltian 2007-07-20
读取不需要同步,但是写可要同步了!之所以HashMap常用,因为它不支持同步,因此读的效率高了
baallee 2007-07-20
HashMap是不提供同步机制的。
建议使用ConcurrentHashMap
发表评论

提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则

您还没有登录,请登录后发表评论

liangguanhui
搜索本博客
博客分类
最近加入圈子
存档
最新评论