论坛首页 Java企业应用论坛

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

浏览 7093 次
精华帖 (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);
    }
   发表时间:2007-07-20  
HashMap是不提供同步机制的。
建议使用ConcurrentHashMap
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics