java - concurrentHashMap源码中的readValueUnderLock(e)存在的意义?

查看:242
本文介绍了java - concurrentHashMap源码中的readValueUnderLock(e)存在的意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

concurrentHashMap源码(JDK1.6)get方法中为什么要readValueUnderLock(e)vnull究竟是怎么产生的?
put方法中有这么一段:
tab[index] = new HashEntry<K,V>(key, hash, first, value);难道在执行构造方法中会存在中间状态?value还没有赋值就能读到?

V get(Object key, int hash) {
    if (count != 0) { // read-volatile
        HashEntry<K,V> e = getFirst(hash);
        while (e != null) {
            if (e.hash == hash && key.equals(e.key)) {
                V v = e.value;
                if (v != null)
                    return v;
                return readValueUnderLock(e); // recheck
            }
            e = e.next;
        }
    }
    return null;
}

V readValueUnderLock(HashEntry<K,V> e) {
    lock();
    try {
        return e.value;
    } finally {
        unlock();
    }
 }

解决方案

e.hash == hash && key.equals(e.key)

前面这一句说明了表里有这个key的,你看看put方法,当valuenull的时候是会跑出异常的:

public V put(K key, V value) {
        Segment<K,V> s;
        if (value == null)
            throw new NullPointerException();
        int hash = hash(key);
        int j = (hash >>> segmentShift) & segmentMask;
        if ((s = (Segment<K,V>)UNSAFE.getObject          // nonvolatile; recheck
             (segments, (j << SSHIFT) + SBASE)) == null) //  in ensureSegment
            s = ensureSegment(j);
        return s.put(key, hash, value, false);
    }

我这是高版本的,可能和你的不一样,但是也是值也是不能为空的。
所以:

if (v != null)
    return v;
return readValueUnderLock(e); // recheck

不为空可以直接返回,如果为空则说明有其他线程在操作它。所以就加了一句。

public V get(Object key) {
        Segment<K,V> s; // manually integrate access methods to reduce overhead
        HashEntry<K,V>[] tab;
        int h = hash(key);
        long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
        if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
            (tab = s.table) != null) {
            for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
                     (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
                 e != null; e = e.next) {
                K k;
                if ((k = e.key) == key || (e.hash == h && key.equals(k)))
                    return e.value;
            }
        }
        return null;
    }

现在版本的get方法把HashEntry<K,V> e弄成UNSAFE.getObjectVolatile()获取,像是volatile的了

这篇关于java - concurrentHashMap源码中的readValueUnderLock(e)存在的意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆