• HashMap 1.7 源码分析


    图示

    测试代码:

    1. public class MapMain {
    2. public static void main(String[] args) {
    3. HashMap map = new HashMap<>();
    4. map.put("hello", "world");
    5. map.get("hello");
    6. }
    7. }

    1.成员变量

    先来看下默认的成员变量

    1. public class HashMap
    2. extends AbstractMap
    3. implements Map, Cloneable, Serializable
    4. {
    5. //默认初始化的数组的长度 是16
    6. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    7. //数组的最大长度
    8. static final int MAXIMUM_CAPACITY = 1 << 30;
    9. //hashMap默认的负载因子
    10. static final float DEFAULT_LOAD_FACTOR = 0.75f;
    11. //hashMap的数组 可以看到默认是个空数组
    12. static final Entry[] EMPTY_TABLE = {};
    13. transient Entry[] table = (Entry[]) EMPTY_TABLE;
    14. //hashMap元素的个数
    15. transient int size;
    16. //阈值 = 数组长度 * 0.75
    17. int threshold;
    18. //负载因子
    19. final float loadFactor;
    20. //修改的次数 fast failed 在iteraotr遍历的时候
    21. transient int modCount;
    22. //rehash的时候可能会使用 基本不会用
    23. static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
    24. ------------------------------------------------------------------------
    25. static class Entry implements Map.Entry {
    26. //hashMap的key
    27. final K key;
    28. //hashMap的value
    29. V value;
    30. //链表的指针指向下一个元素
    31. Entry next;
    32. //可以的hash值 存在这里 在rehash的时候就不用再次计算了
    33. int hash;

    2.默认的构造方法

    1. public HashMap() {
    2. //16 0.75
    3. this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    4. }
    5. public HashMap(int initialCapacity, float loadFactor) {
    6. if (initialCapacity < 0)
    7. throw new IllegalArgumentException("Illegal initial capacity: " +
    8. initialCapacity);
    9. if (initialCapacity > MAXIMUM_CAPACITY)
    10. initialCapacity = MAXIMUM_CAPACITY;
    11. if (loadFactor <= 0 || Float.isNaN(loadFactor))
    12. throw new IllegalArgumentException("Illegal load factor: " +
    13. loadFactor);
    14. //赋值负载因子
    15. this.loadFactor = loadFactor;
    16. //构造方法里面的阈值等于初始化的容量
    17. threshold = initialCapacity;
    18. init();
    19. }
    20. //HashMap的init是空的实现 LinkedHashMap才会有实现
    21. void init() {
    22. }

    3.put方法

    然后再看来下put方法

    1. public V put(K key, V value) {
    2. //如果是空数组 就进去 我们可以看到默认是空的
    3. if (table == EMPTY_TABLE) {
    4. //上面看到空构造方法的阈值是默认的容量 16
    5. inflateTable(threshold);
    6. }
    7. //null值特殊处理 放到数组[0] 位置
    8. if (key == null)
    9. return putForNullKey(value);
    10. //计算hash值 可以忽略不看
    11. // 简单的说就是让0和1 组成的值尽量在下面取余得到的位置更加的散列
    12. int hash = hash(key);
    13. //计算数组下标
    14. //h & (length-1) 使用按位&实现 索引值肯定不会超过 lengh -1
    15. //length是16
    16. // 1100 1010
    17. //& 0000 1111
    18. //= 0000 1010
    19. // 从这我们可以看到 数组长度越大 hash参与 & 的位数越多 散列性也就越强
    20. int i = indexFor(hash, table.length);
    21. //处理key重复的场景 遍历这个单链表
    22. for (Entry e = table[i]; e != null; e = e.next) {
    23. Object k;
    24. //如果hash key相同 并且equal hashMap就认为他们相等
    25. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
    26. //返回旧值使用
    27. V oldValue = e.value;
    28. //使用新值进行覆盖
    29. e.value = value;
    30. e.recordAccess(this);
    31. return oldValue;
    32. }
    33. }
    34. modCount++;
    35. //正常key不相同的进入这里
    36. addEntry(hash, key, value, i);
    37. return null;
    38. }

    3.1 inflateTable

    1. //默认是16
    2. private void inflateTable(int toSize) {
    3. // Find a power of 2 >= toSize
    4. //找到最小的 大于等于toSize的2的次方的数字
    5. int capacity = roundUpToPowerOf2(toSize);
    6. //给阈值赋值为 0.75 * 数组的容量 当然不能超过最大值 MAXIMUM_CAPACITY
    7. threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
    8. //常见hashMap的数组
    9. table = new Entry[capacity];
    10. //可以先忽略
    11. initHashSeedAsNeeded(capacity);
    12. }

    roundUpToPowerOf2方法

    1. private static int roundUpToPowerOf2(int number) {
    2. // assert number >= 0 : "number must be non-negative";
    3. //判断是否大于最大值
    4. int rounded = number >= MAXIMUM_CAPACITY
    5. ? MAXIMUM_CAPACITY
    6. //highestOneBit 找出离number最近的小于等于它的2的次方数 如果是0 就返回1
    7. : (rounded = Integer.highestOneBit(number)) != 0
    8. ?
    9. //最近的小于等于它的2的次方数 二进制有1 就返回它的二倍
    10. //也就是最近的大于等于它的2的次方数
    11. // 否则返回原值
    12. ( (Integer.bitCount(number) > 1) ? rounded << 1 : rounded )
    13. : 1;
    14. return rounded;
    15. }
    16. //转化为二进制数的1的个数 16 -> 0001 0000 ->1 10 -> 0000 1010 -> 2
    17. Integer.bitCount

    highestOneBit

    1. 找出小于等于i的最大的2次方的数
    2. public static int highestOneBit(int i) {
    3. // HD, Figure 3-1
    4. //往后相邻的弄成1
    5. i |= (i >> 1);
    6. //4个1
    7. i |= (i >> 2);
    8. //8个1
    9. i |= (i >> 4);
    10. //16个1
    11. i |= (i >> 8);
    12. //32个1
    13. i |= (i >> 16);
    14. return i - (i >>> 1);
    15. }
    16. 10——> 1010
    17. i |= (i >> 1);
    18. 1010
    19. | 0101
    20. ---------
    21. 1111
    22. i |= (i >> 2);
    23. 1111
    24. | 0111
    25. ---------
    26. 1111
    27. 同理可得
    28. 最后得1111
    29. i - (i >>> 1);
    30. 1111 - 0111 = 1000 = 十进制就是 8

    注意 1+2+4+16 刚好是int有符号整形表示数字的位数

    3.2 putForNullKey

    key 为 null 特殊处理

    1. private V putForNullKey(V value) {
    2. //如果存在就覆盖value
    3. for (Entry e = table[0]; e != null; e = e.next) {
    4. //如果key为null
    5. if (e.key == null) {
    6. V oldValue = e.value;
    7. e.value = value;
    8. e.recordAccess(this);
    9. return oldValue;
    10. }
    11. }
    12. modCount++;
    13. //直接放到数组0的位置
    14. //这个方法后面再看 使用头插法 放入单链表
    15. addEntry(0, null, value, 0);
    16. return null;
    17. }

    4.addEntry

    1. void addEntry(int hash, K key, V value, int bucketIndex) {
    2. //如果size大于等会扩容的阈值 并且当前要添加元素的数组已经有元素了 才会进行扩容
    3. if ((size >= threshold) && (null != table[bucketIndex])) {
    4. //扩容 可以看到新的容量是以前的2倍
    5. resize(2 * table.length);
    6. hash = (null != key) ? hash(key) : 0;
    7. bucketIndex = indexFor(hash, table.length);
    8. }
    9. //将元素放入数组中
    10. createEntry(hash, key, value, bucketIndex);
    11. }
    12. void createEntry(int hash, K key, V value, int bucketIndex) {
    13. //去除数组目前的元素 也就是链表的头部
    14. Entry e = table[bucketIndex];
    15. //使用头插法插入新的元素
    16. //新元素的next属性就是上面的e 就得数组的链表的头部
    17. table[bucketIndex] = new Entry<>(hash, key, value, e);
    18. size++;
    19. }

    5.resize

    再来看下扩容的代码

    1. //newCapacity = 2 * oldCapacity
    2. void resize(int newCapacity) {
    3. Entry[] oldTable = table;
    4. int oldCapacity = oldTable.length;
    5. if (oldCapacity == MAXIMUM_CAPACITY) {
    6. threshold = Integer.MAX_VALUE;
    7. return;
    8. }
    9. //创建新的数组
    10. Entry[] newTable = new Entry[newCapacity];
    11. //转移元素
    12. transfer(newTable, initHashSeedAsNeeded(newCapacity));
    13. table = newTable;
    14. //重新计算阈值
    15. threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    16. }

    initHashSeedAsNeeded

    如果这个值是true会重新计算hash值

    是false则使用先前计算好的(在entry成员属性hash)

    简单的描述下逻辑:

    "jdk.map.althashing.threshold" 只有在被赋值的时候才有可能返回true 因为默认的是Int的最大值

    1. final boolean initHashSeedAsNeeded(int capacity) {
    2. boolean currentAltHashing = hashSeed != 0;
    3. //sun.misc.VM.isBooted() 为
    4. //capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD 表示容量大于需要rehash的阈值
    5. boolean useAltHashing = sun.misc.VM.isBooted() &&
    6. (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
    7. //currentAltHashing 默认是true
    8. // ^ 相同为真 不同为false
    9. //表示只有useAltHashing 为true的时候才会返回true
    10. boolean switching = currentAltHashing ^ useAltHashing;
    11. if (switching) {
    12. hashSeed = useAltHashing
    13. ? sun.misc.Hashing.randomHashSeed(this)
    14. : 0;
    15. }
    16. return switching;
    17. }
    18. //Holder.ALTERNATIVE_HASHING_THRESHOLD 默认是int类型的最大值 也就返回false
    19. private static class Holder {
    20. /**
    21. * Table capacity above which to switch to use alternative hashing.
    22. */
    23. static final int ALTERNATIVE_HASHING_THRESHOLD;
    24. static {
    25. //从jvm参数中获取jdk.map.althashing.threshold的值 rehash的阈值
    26. String altThreshold = java.security.AccessController.doPrivileged(
    27. new sun.security.action.GetPropertyAction(
    28. "jdk.map.althashing.threshold"));
    29. int threshold;
    30. try {
    31. threshold = (null != altThreshold)
    32. ? Integer.parseInt(altThreshold)
    33. : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;
    34. // disable alternative hashing if -1
    35. if (threshold == -1) {
    36. threshold = Integer.MAX_VALUE;
    37. }
    38. if (threshold < 0) {
    39. throw new IllegalArgumentException("value must be positive integer.");
    40. }
    41. } catch(IllegalArgumentException failed) {
    42. throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
    43. }
    44. //不赋值就是int的最大值
    45. ALTERNATIVE_HASHING_THRESHOLD = threshold;
    46. }
    47. }

    使用debug 啥也不指定 默认为true

    transfer方法

    1. //newTable 新的数组
    2. void transfer(Entry[] newTable 新的数组, boolean rehash) {
    3. int newCapacity = newTable.length;
    4. //遍历数组
    5. for (Entry e : table) {
    6. //遍历单链表 使用头插法进行迁移
    7. while(null != e) {
    8. Entry next = e.next;
    9. //是否重新计算hash值
    10. if (rehash) {
    11. e.hash = null == e.key ? 0 : hash(e.key);
    12. }
    13. int i = indexFor(e.hash, newCapacity);
    14. e.next = newTable[i];
    15. newTable[i] = e;
    16. e = next;
    17. }
    18. }
    19. }

    扩容图示:

    新的位置是 原位置 或者 原位置 + oldTable.length

    使用的是头插法进行扩容 链表元素顺序会反转

    6.循环链表

    多线程会出现扩容 出现循环链表 形成死循环

    transfer(Entry[] newTable, boolean rehash)

    转移所有的 Entry 从当前 table 到新 table,被多个线程调用时可能会出现循环链表,线程不安全。

    假设 table 中的某个位置如下图所示(有三个 Entry),thread1 和 thread2 都刚刚执行完 这个位置的第一次 while 循环的 Entry next = e.next;

    thread1 执行完 while 循环

    thread2 执行完第一次 while 循环

    thread2 执行完第二次 while 循环

    thread2 执行完第三次 while 循环

    微信公众号:  后端小白养成记

    欢迎关注:

     

  • 相关阅读:
    为树莓派打实时preempt_rt补丁
    低代码平台的分类及选择参考
    如何将 Helm Chart 推送至 Harbor ?
    四数之和(LeetCode)
    C语言学习笔记
    Vite + React + Ant Design构建项目
    Java如何读取OS环境变量吗?
    Java随笔-CountDownLatch
    【GitLab】-HTTP 500 curl 22 The requested URL returned error: 500~SSH解决
    【LeetCode】Day177-统计一致字符串的数目
  • 原文地址:https://blog.csdn.net/qq_35529801/article/details/126430974