java - ConcurrentHashMap中的get()方法为什么可以不加锁?
问题描述
public V get(Object key) {Segment<K,V> s; // manually integrate access methods to reduce overheadHashEntry<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; }
为什么Vector的get就需要使用synchronized来加锁而ConcurrentHashMap则不需要?而且CopyOnWriteArrayList也是使用了写时复制还能实现读写并行,而显然ConcrrentHashMap并没有实现写时复制,它是怎么保证读写并行时不会读取到不一致中间状态的呢?
问题解答
回答1:这篇文章解释的挺好的
相关文章: