设为首页 加入收藏

TOP

ConcurrentHashMap 源码分析(二)
2015-11-21 00:57:35 来源: 作者: 【 】 浏览:6
Tags:ConcurrentHashMap 源码 分析
lue, boolean onlyIfAbsent) { HashEntry node = tryLock() ? null : scanAndLockForPut(key, hash, value); V oldValue; try { HashEntry [] tab = table; int index = (tab.length - 1) & hash; HashEntry first = entryAt(tab, index); for (HashEntry e = first;;) { if (e != null) { K k; if ((k = e.key) == key || (e.hash == hash && key.equals(k))) { oldValue = e.value; if (!onlyIfAbsent) { e.value = value; ++modCount; } break; } e = e.next; } else { if (node != null) node.setNext(first); else node = new HashEntry (hash, key, value, first); int c = count + 1; if (c > threshold && tab.length < MAXIMUM_CAPACITY) rehash(node); else setEntryAt(tab, index, node); ++modCount; count = c; oldValue = null; break; } } } finally { unlock(); } return oldValue; } ?

get()

    public V get(Object key) {
        Segment
   
     s; // manually integrate access methods to reduce overhead
        HashEntry
    
     [] tab; int h = hash(key.hashCode()); long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE; if ((s = (Segment
     
      )UNSAFE.getObjectVolatile(segments, u)) != null && (tab = s.table) != null) { for (HashEntry
      
        e = (HashEntry
       
        ) 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; }
       
      
     
    
   

原理很简单先定位到segment,然后定位到实体。并且通过getObjectVolatie保证能够读到最新的数据。
总结:concurrentHashMap实现涉及到很多多线程的知识和java内存模型这方面的知识,如果没有足够的能力,介意不要模仿,但是我们可以学习它的思想以及是如何实现的。


?

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++再次理解虚表 下一篇hihoCoder - 1121 - 二分图判定

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: