_/**_ _ * Basic hash bin node, used for most entries. (See below for_ _ * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)_ _ */_ staticclassNode<K,V> implementsMap.Entry<K,V> { finalint hash; final K key; V value; Node<K,V> next;
_/**_ _ * Computes key.hashCode() and spreads (XORs) higher bits of hash_ _ * to lower. Because the table uses power-of-two masking, sets of_ _ * hashes that vary only in bits above the current mask will_ _ * always collide. (Among known examples are sets of Float keys_ _ * holding consecutive whole numbers in small tables.) So we_ _ * apply a transform that spreads the impact of higher bits_ _ * downward. There is a tradeoff between speed, utility, and_ _ * quality of bit-spreading. Because many common sets of hashes_ _ * are already reasonably distributed (so don't benefit from_ _ * spreading), and because we use trees to handle large sets of_ _ * collisions in bins, we just XOR some shifted bits in the_ _ * cheapest possible way to reduce systematic lossage, as well as_ _ * to incorporate impact of the highest bits that would otherwise_ _ * never be used in index calculations because of table bounds._ _ */_ staticfinalinthash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
_/**_ _ * Replaces all linked nodes in bin at index for given hash unless_ _ * table is too small, in which case resizes instead._ _ */_ finalvoidtreeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; if (tab == null || (n = tab.length) < _MIN_TREEIFY_CAPACITY_) resize(); elseif ((e = tab[index = (n - 1) & hash]) != null) { TreeNode<K,V> hd = null, tl = null; do { TreeNode<K,V> p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) hd.treeify(tab); } }
_/**_ _ * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn_ _ * extends Node) so can be used as extension of either regular or_ _ * linked node._ _ */_ staticfinalclassTreeNode<K,V> extendsLinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; // red-black tree links TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); }
_/**_ _ * Returns root of tree containing this node._ _ */_ _ _final TreeNode<K,V> root() { for (TreeNode<K,V> r = this, p;;) { if ((p = r.parent) == null) return r; r = p; } } }
/** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with {@code key}, or * {@code null} if there was no mapping for {@code key}. * (A {@code null} return can also indicate that the map * previously associated {@code null} with {@code key}.) */ public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
/** * Implements Map.put and related methods. * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. * @return previous value, or null if none */ final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; elseif (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (intbinCount=0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key VoldValue= e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); returnnull; }
_/**_ _ * Returns the value to which the specified key is mapped,_ _ * or {_**@code **_null} if this map contains no mapping for the key._ _ *_ _ * <p>More formally, if this map contains a mapping from a key_ _ * {_**@code **_k} to a value {_**@code **_v} such that {_**@code **_(key==null ? k==null :_ _ * key.equals(k))}, then this method returns {_**@code **_v}; otherwise_ _ * it returns {_**@code **_null}. (There can be at most one such mapping.)_ _ *_ _ * <p>A return value of {_**@code **_null} does not <i>necessarily</i>_ _ * indicate that the map contains no mapping for the key; it's also_ _ * possible that the map explicitly maps the key to {_**@code **_null}._ _ * The {_**@link **_#containsKey containsKey} operation may be used to_ _ * distinguish these two cases._ _ *_ _ * _**@see **_#put(Object, Object)_ _ */_ public V get(Object key) { Node<K,V> e; return (e = getNode(key)) == null ? null : e.value; }
_/**_ _ * Implements Map.get and related methods._ _ *_ _ * _**@param **_key the key_ _ * _**@return **_the node, or null if none_ _ */_ final Node<K,V> getNode(Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & (hash = _hash_(key))]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } returnnull; }
_/**_ _ * Constructs a new set containing the elements in the specified_ _ * collection. The {_**@code **_HashMap} is created with default load factor_ _ * (0.75) and an initial capacity sufficient to contain the elements in_ _ * the specified collection._ _ *_ _ * _**@param **_c the collection whose elements are to be placed into this set_ _ * _**@throws **_NullPointerException if the specified collection is null_ _ */_ publicHashSet(Collection<? extends E> c) { map = newHashMap<>(Math._max_((int) (c.size()/.75f) + 1, 16)); addAll(c); }
_/**_ _ * Constructs a new, empty set; the backing {_**@code **_HashMap} instance has_ _ * the specified initial capacity and the specified load factor._ _ *_ _ * _**@param **_initialCapacity the initial capacity of the hash map_ _ * _**@param **_loadFactor the load factor of the hash map_ _ * _**@throws **_IllegalArgumentException if the initial capacity is less_ _ * than zero, or if the load factor is nonpositive_ _ */_ publicHashSet(int initialCapacity, float loadFactor) { map = newHashMap<>(initialCapacity, loadFactor); }
_/**_ _ * Constructs a new, empty set; the backing {_**@code **_HashMap} instance has_ _ * the specified initial capacity and default load factor (0.75)._ _ *_ _ * _**@param **_initialCapacity the initial capacity of the hash table_ _ * _**@throws **_IllegalArgumentException if the initial capacity is less_ _ * than zero_ _ */_ publicHashSet(int initialCapacity) { map = newHashMap<>(initialCapacity); }
_/**_ _ * Constructs a new, empty linked hash set. (This package private_ _ * constructor is only used by LinkedHashSet.) The backing_ _ * HashMap instance is a LinkedHashMap with the specified initial_ _ * capacity and the specified load factor._ _ *_ _ * _**@param **_initialCapacity the initial capacity of the hash map_ _ * _**@param **_loadFactor the load factor of the hash map_ _ * _**@param **_dummy ignored (distinguishes this_ _ * constructor from other int, float constructor.)_ _ * _**@throws **_IllegalArgumentException if the initial capacity is less_ _ * than zero, or if the load factor is nonpositive_ _ */_ HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = newLinkedHashMap<>(initialCapacity, loadFactor); }
add 方法
插入元素时,调用 HashMap 中的 put 方法,key 为插入元素,value 为默认的 Object 对象
// Dummy value to associate with an Object in the backing Map privatestaticfinal Object _PRESENT _= newObject();
/** * Adds the specified element to this set if it is not already present. * More formally, adds the specified element {@code e} to this set if * this set contains no element {@code e2} such that * {@code Objects.equals(e, e2)}. * If this set already contains the element, the call leaves the set * unchanged and returns {@code false}. * * @param e element to be added to this set * @return {@code true} if this set did not already contain the specified * element */ publicbooleanadd(E e) { return map.put(e, PRESENT)==null; }
ConcurrentHashMap 源码
ConcurrentHashMap 底层与 HashMap 相同,在具体操作上使用了 CAS (Compare-And-Swap)操作与 synchronized 锁来保证线程安全。
initialTable 方法
实现了延迟初始化,只有在真正需要时才会分配和初始化内部数据结构,通过 CAS 操作来保证多个线程在并发情况下能够安全地初始化哈希表,具体流程如下:
_/**_ _ * Maps the specified key to the specified value in this table._ _ * Neither the key nor the value can be null._ _ *_ _ * <p>The value can be retrieved by calling the {_**@code **_get} method_ _ * with a key that is equal to the original key._ _ *_ _ * _**@param **_key key with which the specified value is to be associated_ _ * _**@param **_value value to be associated with the specified key_ _ * _**@return **_the previous value associated with {_**@code **_key}, or_ _ * {_**@code **_null} if there was no mapping for {_**@code **_key}_ _ * _**@throws **_NullPointerException if the specified key or value is null_ _ */_ public V put(K key, V value) { return putVal(key, value, false); }
_/** Implementation for put and putIfAbsent */_ final V putVal(K key, V value, boolean onlyIfAbsent) { if (key == null || value == null) thrownewNullPointerException(); inthash= _spread_(key.hashCode()); intbinCount=0; for (Node<K,V>[] tab = table;;) { Node<K,V> f; int n, i, fh; K fk; V fv; if (tab == null || (n = tab.length) == 0) tab = initTable(); elseif ((f = _tabAt_(tab, i = (n - 1) & hash)) == null) { if (_casTabAt_(tab, i, null, newNode<K,V>(hash, key, value))) break; // no lock when adding to empty bin } elseif ((fh = f.hash) == _MOVED_) tab = helpTransfer(tab, f); elseif (onlyIfAbsent // check first node without acquiring lock && fh == hash && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null) return fv; else { VoldVal=null; synchronized (f) { if (_tabAt_(tab, i) == f) { if (fh >= 0) { binCount = 1; for (Node<K,V> e = f;; ++binCount) { K ek; if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { oldVal = e.val; if (!onlyIfAbsent) e.val = value; break; } Node<K,V> pred = e; if ((e = e.next) == null) { pred.next = newNode<K,V>(hash, key, value); break; } } } elseif (f instanceof TreeBin) { Node<K,V> p; binCount = 2; if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) p.val = value; } } elseif (f instanceof ReservationNode) thrownewIllegalStateException("Recursive update"); } } if (binCount != 0) { if (binCount >= _TREEIFY_THRESHOLD_) treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } addCount(1L, binCount); returnnull; }