Java1.8-HashMap

HashMap

                    

hashmap本质数组+链表+红黑树(链地址法,解决hash冲突问题)。根据key取得hash值,然后计算出数组下标,如果多个key对应到同一个下标,就用链表串起来,新插入的在前面。

 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
 }

^ 亦或:两个数转为二进制,然后从高位开始比较,如果相同则为0,不相同则为1。

public HashMap(int initialCapacity, float loadFactor) {  
  if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
       if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY;
       if (loadFactor <= 0 || Float.isNaN(loadFactor))  throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
       this.loadFactor = loadFactor;
       this.threshold = tableSizeFor(initialCapacity)
        //最多容纳的Entry数,如果当前元素个数多于这个就要扩容
}
public V get(Object key) {
  Node<K,V> e;
  return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
  Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
  if ((tab = table) != null && (n = tab.length) > 0 &&
   (first = tab[(n - 1) & hash]) != 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);
    }
  }
       return null;
}
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; //扩充空表
   //&:两个数都转为二进制,然后从高位开始比较,如果两个数都为1则为1,否则为0。取最小
        if ((p = tab[i = (n - 1) & hash]) == null)  //p取hash链头,并判断是否已存在hash链
            tab[i] = newNode(hash, key, value, null);   //赋值-新hash链
        else {
     //存在hash链,hash链中key值不唯一
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k)))) //p同key
                e = p; //取原值
            else if (p instanceof TreeNode) //红黑树 链长>8
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) { //从表链中取数据e:p的下一个;判断是否有p以外(其他k)的Node
                        p.next = newNode(hash, key, value, null); //插入新值
                        if (binCount >= TREEIFY_THRESHOLD - 1)  // 8-1
        treeifyBin(tab, hash);

/** TREEIFY_THRESHOLD
 * The bin count threshold for using a tree rather than list for a
 * bin.  Bins are converted to trees when adding an element to a
 * bin with at least this many nodes. The value must be greater
 * than 2 and should be at least 8 to mesh with assumptions in
 * tree removal about conversion back to plain bins upon
 * shrinkage.
 */
//
超过数量装换list为tree break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) //e同key break; p = e; //为迭代 } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue;    }   }   ++modCount; /** modCount * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). */
//
fail-fast 机制是java集合(Collection)中的一种错误机制。当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。
//内部结构发生变化指的是结构发生变化,例如put新键值对,但是某个key对应的value值被覆盖不属于结构变化
//if (modCount != expectedModCount) throw new ConcurrentModificationException();   if (++size > threshold) resize();   afterNodeInsertion(evict);   return null; }
static final int tableSizeFor(int cap) { //10
        int n = cap - 1; //9
        n |= n >>> 1; //13
        n |= n >>> 2; //15  
        n |= n >>> 4;//15
        n |= n >>> 8;//15
        n |= n >>> 16;//15
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;//16
       //10(1001+0001)—— 16(1111+0001) 即位数补满1再+1
    
final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;

// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY(16).) —— threshold

        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) { //原链表超过最大容量
                threshold = Integer.MAX_VALUE;
                return oldTab; //不扩容
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;

/**
 * Indicates that the named compiler warnings should be suppressed in the
 * annotated element (and in all program elements contained in the annotated
 * element).  Note that the set of warnings suppressed in a given element is
 * a superset of the warnings suppressed in all containing elements.  For
 * example, if you annotate a class to suppress one warning and annotate a
 * method to suppress another, both warnings will be suppressed in the method.
 *
 * <p>As a matter of style, programmers should always use this annotation
 * on the most deeply nested element where it is effective.  If you want to
 * suppress a warning in a particular method, you should annotate that
 * method rather than its class.
 *
 * @author Josh Bloch
 * @since 1.5
 * @jls 4.8 Raw Types
 * @jls 4.12.2 Variables of Reference Type
 * @jls 5.1.9 Unchecked Conversion
 * @jls 5.5.2 Checked Casts and Unchecked Casts
 * @jls 9.6.3.5 @SuppressWarnings
 */
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {...}
     @SuppressWarnings({"rawtypes","unchecked"})
   //SuppressWarnings压制警告,即去除警告 rawtypes是说传参时也要传递带泛型的参数

    Node
<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table
= newTab; if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; //按二进制取各位最小值,重算hash值,扩容*2-1即高位+1

 

                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); //红黑树
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;//一前一后
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next; //取链表下一个
                            if ((e.hash & oldCap) == 0) { //连续性分奇偶,在hash中,初值为0
//比如 oldCap = 9 —— 1001&0001=0001;1001&0010=0000;1001&0011=0001;1001&0100=00001001&0101=0001;1001&0110=0000;
if (loTail == null) loHead = e; // else loTail.next = e; //为当前next赋值 loTail = e;//尾指针,辅助下一次next的赋值
}
else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null);
//times:1—hi—next=2,e=1;hiHead=hiTail=e=1;loHead=loTail=null;
//times:2—lo—next=3,e=2;hiHead=hiTail=e=1;loHead=loTail=loTail.next=2;
//times:3—hi—next=4,e=3;hiTail=hiTail.next=3;loHead=loTail=loTail.next=2;
//times:4—lo—next=5,e=4;hiTail=hiTail.next=3;loTail=loTail.next=4;
//hiHead=1;loHead=2;hiHead.next.next=2.next=loHead.next=3
if (loTail != null) { loTail.next = null; newTab[j] = loHead;//奇数一列 } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead;//偶数一列 } } } } } return newTab; }

 线程安全性

HashMap是线程不安全的

public class HashMapInfiniteLoop {  
    private static HashMap<Integer,String> map = new HashMap<Integer,String>(20.75f);  
    public static void main(String[] args) {  
        map.put(5"C");  
        new Thread("Thread1") {  
            public void run() {  
                map.put(7, "B");  
                System.out.println(map);  
            };  
        }.start();  
        new Thread("Thread2") {  
            public void run() {  
                map.put(3, "A);  
                System.out.println(map);  
            };  
        }.start();        
    }  
}

 thread1和thread2都触发了resize扩容。此时为5(1)、7(1)、3(1) 假设hash是mod2

扩容后结果应分别是0:{},1:{5,3},2:{},3:{7}

考虑到并行,假设thread1阻塞在resize的next = e.next;(while ((e = next) != null)循环中)  ,此时e=5, 5.next=7,7.next=3
thread2扩容完成,此时5.next=3,3.next=null,7.next=null

thread1回调:e不变为5,但此时next=5.next=3,3.next=null;即0:{},1:{5},2:{0},3:{3}

好像会漏数据但不至于闭环? 不安全体现在没有锁

参考:

HashMap实现原理及源码分析-http://www.cnblogs.com/chengxiao/p/6059914.html

HashMap和ConcurrentHashMap浅析-http://blog.csdn.net/zldeng19840111/article/details/6703104

Java中的几个HashMap/ConcurrentHashMap实现分析-http://www.importnew.com/19685.html

Java8系列之重新认识HashMap-http://www.importnew.com/20386.html

JDK1.8HashMap原理和源码分析-https://max.book118.com/html/2016/1215/72615285.shtm

posted @ 2018-03-02 16:51  wzbin  阅读(491)  评论(0编辑  收藏  举报