激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務(wù)器之家:專(zhuān)注于服務(wù)器技術(shù)及軟件下載分享
分類(lèi)導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術(shù)|正則表達(dá)式|

香港云服务器
服務(wù)器之家 - 編程語(yǔ)言 - JAVA教程 - Java HashMap源碼及并發(fā)環(huán)境常見(jiàn)問(wèn)題解決

Java HashMap源碼及并發(fā)環(huán)境常見(jiàn)問(wèn)題解決

2020-09-15 13:53yaominghui JAVA教程

這篇文章主要介紹了Java HashMap源碼及并發(fā)環(huán)境常見(jiàn)問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

HashMap源碼簡(jiǎn)單分析:

1 一切需要從HashMap屬性字段說(shuō)起:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/** The default initial capacity - MUST be a power of two. 初始容量 */
  static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
 
  /**
   * The maximum capacity, used if a higher value is implicitly specified
   * by either of the constructors with arguments.
   * MUST be a power of two <= 1<<30. 最大容量
   */
  static final int MAXIMUM_CAPACITY = 1 << 30;
 
  /**
   * The load factor used when none specified in constructor.    * 默認(rèn)的負(fù)載因子,當(dāng)map的size>=負(fù)載因子*capacity時(shí)候并且插入元素時(shí)候的table[i]!=null進(jìn)行擴(kuò)容   * 擴(kuò)容判斷邏輯:java.util.HashMap#addEntry函數(shù)中   *
   */
  static final float DEFAULT_LOAD_FACTOR = 0.75f;
 
  /**
   * An empty table instance to share when the table is not inflated.
   */
  static final Entry<?,?>[] EMPTY_TABLE = {};
 
  /**
   * The table, resized as necessary. Length MUST Always be a power of two. 哈希表
   */
  transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
 
  /**
   * The number of key-value mappings contained in this map. map的大小
   */
  transient int size;
 
  /**
   * The next size value at which to resize (capacity * load factor).
   * @serial
   */
  // If table == EMPTY_TABLE then this is the initial capacity at which the
  // table will be created when inflated. 擴(kuò)容的閾值 = capacity * 負(fù)載因子
  int threshold;
 
  /**
   * The load factor for the hash table. 負(fù)載因子,默認(rèn)是0.75,可以在創(chuàng)建HashMap時(shí)候通過(guò)構(gòu)造函數(shù)指定
   *
   * @serial
   */
  final float loadFactor;
 
  /**
   * 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).   * 修改次數(shù):例如進(jìn)行rehash或者返回hashMap視圖時(shí)候如果發(fā)生修改可以fast-fail
   */
  transient int modCount;
 
  /**
   * The default threshold of map capacity above which alternative hashing is
   * used for String keys. Alternative hashing reduces the incidence of
   * collisions due to weak hash code calculation for String keys.
   * <p/>
   * This value may be overridden by defining the system property
   * {@code jdk.map.althashing.threshold}. A property value of {@code 1}
   * forces alternative hashing to be used at all times whereas
   * {@code -1} value ensures that alternative hashing is never used.   * rehash時(shí)候判斷的一個(gè)閾值
   */
  static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;

2: 接下來(lái)查看一下HashMap的put方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
   * 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 <tt>key</tt>, or
   *     <tt>null</tt> if there was no mapping for <tt>key</tt>.
   *     (A <tt>null</tt> return can also indicate that the map
   *     previously associated <tt>null</tt> with <tt>key</tt>.)
   */
  public V put(K key, V value) {
    if (table == EMPTY_TABLE) {//初始化哈希表
      inflateTable(threshold);
    }
    if (key == null) //如果key 為null 存儲(chǔ)到table[0]位置
      return putForNullKey(value);
    int hash = hash(key); //計(jì)算hash值
    int i = indexFor(hash, table.length);//計(jì)算entry在table中的位置
    //for循環(huán)邏輯用于修改key對(duì)應(yīng)的value的
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
      Object k;
      if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
        V oldValue = e.value;
        e.value = value;
        e.recordAccess(this);
        return oldValue;//如果是更新返回舊值
      }
    }
    //修改次數(shù)++
    modCount++;
    //添加元素到哈希表中
    addEntry(hash, key, value, i);
    // 如果是添加元素則返回null
    return null;
  }

3 put中調(diào)用的inflateTable方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
   * Inflates the table.
   */
  private void inflateTable(int toSize) {
    // Find a power of 2 >= toSize
    //計(jì)算大于等于toSize的最小的2的整數(shù)次冪的值
    int capacity = roundUpToPowerOf2(toSize);
    //計(jì)算擴(kuò)容閾值
    threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
    //初始化哈希表
    table = new Entry[capacity];
    //更新一下rehash的判斷條件,便于以后判斷是否rehash
    initHashSeedAsNeeded(capacity);
  }

4 put方法中調(diào)用的indexFor方法:

?
1
2
3
4
5
6
7
8
/**
   * Returns index for hash code h. 返回哈希值對(duì)應(yīng)的哈希表索引
   */
  static int indexFor(int h, int length) {
    // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
   //使用&操作,而不使用取余原因:均勻分布在哈希表中 。length-1目的是:由于table的長(zhǎng)度都是2的整數(shù)次冪進(jìn)行擴(kuò)容,length-1的二進(jìn)制全是1,計(jì)算效率高
    return h & (length-1);
  }

5 put方法中調(diào)用的addEntry方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
   * Adds a new entry with the specified key, value and hash code to
   * the specified bucket. It is the responsibility of this
   * method to resize the table if appropriate.
   *
   * Subclass overrides this to alter the behavior of put method.
   */
  void addEntry(int hash, K key, V value, int bucketIndex) {
   //判斷是否擴(kuò)容,只有size大于等于閾值而且當(dāng)前插入table[i]!=null(就是able[i]已經(jīng)被占用則擴(kuò)容)
   if ((size >= threshold) && (null != table[bucketIndex])) {
      resize(2 * table.length);
      hash = (null != key) ? hash(key) : 0;
      //如果需要擴(kuò)容的話(huà)則需要更新再次重新計(jì)算哈希表位置
      bucketIndex = indexFor(hash, table.length);
    }
    //將值插入到哈希表中
    createEntry(hash, key, value, bucketIndex);
  }

6 addEntry方法中調(diào)用的createEntry方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
   * Like addEntry except that this version is used when creating entries
   * as part of Map construction or "pseudo-construction" (cloning,
   * deserialization). This version needn't worry about resizing the table.
   *
   * Subclass overrides this to alter the behavior of HashMap(Map),
   * clone, and readObject.
   */
  void createEntry(int hash, K key, V value, int bucketIndex) {
    // 獲取到哈希表指定位置
    Entry<K,V> e = table[bucketIndex];
    // 鏈表的頭插入方式進(jìn)行插入,插入邏輯在Entry的構(gòu)造器中。然后將新節(jié)點(diǎn)存儲(chǔ)到 table[bucketIndex]中
    table[bucketIndex] = new Entry<>(hash, key, value, e);
    size++;//更新size即可
  }

Entry構(gòu)造器:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
   *
   * @param h hash值
   * @param k key
   * @param v value
   * @param n 原始鏈表
   */
  Entry(int h, K k, V v, Entry<K,V> n) {
    value = v;
    //將原始鏈表接該節(jié)點(diǎn)后面
    next = n;
    key = k;
    hash = h;
  }

7 接下來(lái)看一下java.util.HashMap#addEntry擴(kuò)容機(jī)制:

當(dāng)進(jìn)行擴(kuò)容時(shí)候需要重新計(jì)算哈希值和在哈希表中的位置。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
void addEntry(int hash, K key, V value, int bucketIndex) {
    //滿(mǎn)足擴(kuò)容條件進(jìn)行擴(kuò)容
    if ((size >= threshold) && (null != table[bucketIndex])) {
      //擴(kuò)容,2倍進(jìn)行擴(kuò)容
      resize(2 * table.length);
      //重新計(jì)算哈數(shù)值
      hash = (null != key) ? hash(key) : 0;
      //重新計(jì)算哈希表中的位置
      bucketIndex = indexFor(hash, table.length);
    }
 
    createEntry(hash, key, value, bucketIndex);
  }

接下來(lái)看一下java.util.HashMap#resize方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
   * Rehashes the contents of this map into a new array with a
   * larger capacity. This method is called automatically when the
   * number of keys in this map reaches its threshold.
   *
   * If current capacity is MAXIMUM_CAPACITY, this method does not
   * resize the map, but sets threshold to Integer.MAX_VALUE.
   * This has the effect of preventing future calls.
   *
   * @param newCapacity the new capacity, MUST be a power of two;
   *    must be greater than current capacity unless current
   *    capacity is MAXIMUM_CAPACITY (in which case value
   *    is irrelevant).
   */
  void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {//判斷當(dāng)前old容量是否最最大容量,是的話(huà)更新閾值
      threshold = Integer.MAX_VALUE;
      return;
    }
    //創(chuàng)建新的表
    Entry[] newTable = new Entry[newCapacity];
    //元素轉(zhuǎn)移,根據(jù)initHashSeedAsNeeded結(jié)果判斷是否進(jìn)行rehash
    transfer(newTable, initHashSeedAsNeeded(newCapacity));
    // 新表賦給table
    table = newTable;
    //更新閾值
    threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
  }

關(guān)于HashMap在并發(fā)情況下的常見(jiàn)問(wèn)題,其實(shí)在多線(xiàn)程環(huán)境下使用HashMap本來(lái)就是有風(fēng)險(xiǎn)錯(cuò)誤的,但是一般面試卻喜歡這么問(wèn),下面列舉一下自己印象中的常見(jiàn)問(wèn)題:

1:在進(jìn)行擴(kuò)容時(shí)候,其他線(xiàn)程是否可以進(jìn)行進(jìn)行插入操作(多線(xiàn)程環(huán)境下可能會(huì)導(dǎo)致HashMap進(jìn)入死循環(huán),此處暫不考慮)?

答:首先HashMap就不是一個(gè)線(xiàn)程安全的容器,所以在多線(xiàn)程環(huán)境下使用就是錯(cuò)誤的。其次在擴(kuò)容時(shí)候可以進(jìn)行插入的,但是不安全。例如:

當(dāng)主線(xiàn)程在調(diào)用transfer方法進(jìn)行復(fù)制元素:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
   * Transfers all entries from current table to newTable.
   */
  void transfer(Entry[] newTable, boolean rehash) {
    int newCapacity = newTable.length;
    for (Entry<K,V> e : table) {
      while(null != e) {
        Entry<K,V> next = e.next;
        if (rehash) {
          e.hash = null == e.key ? 0 : hash(e.key);
        }
        int i = indexFor(e.hash, newCapacity);
        e.next = newTable[i];
        newTable[i] = e;
        e = next;
      }
    }
  }

此時(shí)另一個(gè)線(xiàn)程在添加新元素是可以的,新元素添加到table中。如果子線(xiàn)程需要擴(kuò)容的話(huà)可以進(jìn)行擴(kuò)容,然后將新容器賦給table。而此時(shí)主線(xiàn)程轉(zhuǎn)移元素的工作就是將table中元素轉(zhuǎn)移到newTable中。注意main線(xiàn)程的transfer方法:

如果main線(xiàn)程剛進(jìn)入transfer方法時(shí)候newTable大小是32的話(huà),由于子線(xiàn)程的添加操作導(dǎo)致table此時(shí)元素如果有128的話(huà)。則128個(gè)元素就會(huì)存儲(chǔ)到大小為32的newTable中(此處不會(huì)擴(kuò)容)。這就會(huì)導(dǎo)致HashMap性能下降!!!

可以使用多線(xiàn)程環(huán)境進(jìn)行debug查看即可確定(推薦Idea的debug,的確強(qiáng)大,尤其是Evaluate Expression功能)。

2:進(jìn)行擴(kuò)容時(shí)候元素是否需要重新Hash?

這個(gè)需要具體情況判斷,調(diào)用initHashSeedAsNeeded方法判斷(判斷邏輯這里先不介紹)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
   * Rehashes the contents of this map into a new array with a
   * larger capacity. This method is called automatically when the
   * number of keys in this map reaches its threshold.
   *
   * If current capacity is MAXIMUM_CAPACITY, this method does not
   * resize the map, but sets threshold to Integer.MAX_VALUE.
   * This has the effect of preventing future calls.
   *
   * @param newCapacity the new capacity, MUST be a power of two;
   *    must be greater than current capacity unless current
   *    capacity is MAXIMUM_CAPACITY (in which case value
   *    is irrelevant).
   */
  void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
      threshold = Integer.MAX_VALUE;
      return;
    }
 
    Entry[] newTable = new Entry[newCapacity];
    //initHashSeedAsNeeded 判斷是否需要重新Hash
    transfer(newTable, initHashSeedAsNeeded(newCapacity));
    table = newTable;
    threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
  }

然后進(jìn)行轉(zhuǎn)移元素:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
   * Transfers all entries from current table to newTable.
   */
  void transfer(Entry[] newTable, boolean rehash) {
    int newCapacity = newTable.length;
    //多線(xiàn)程環(huán)境下,如果其他線(xiàn)程導(dǎo)致table快速擴(kuò)大。newTable在此處無(wú)法擴(kuò)容會(huì)導(dǎo)致性能下降。但是如果后面有再次調(diào)用put方法的話(huà)可以再次觸發(fā)resize。
    for (Entry<K,V> e : table) {
      while(null != e) {
        Entry<K,V> next = e.next;
        if (rehash) { //判斷是否需要重新Hash
          e.hash = null == e.key ? 0 : hash(e.key);
        }
        int i = indexFor(e.hash, newCapacity);
        e.next = newTable[i];
        newTable[i] = e;
        e = next;
      }
    }
  }

3:如何判斷是否需要重新Hash?

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
   * Initialize the hashing mask value. We defer initialization until we
   * really need it.
   */
  final boolean initHashSeedAsNeeded(int capacity) {
 
    // hashSeed降低hash碰撞的hash種子,初始值為0
    boolean currentAltHashing = hashSeed != 0;
    //ALTERNATIVE_HASHING_THRESHOLD: 當(dāng)map的capacity容量大于這個(gè)值的時(shí)候并滿(mǎn)足其他條件時(shí)候進(jìn)行重新hash
    boolean useAltHashing = sun.misc.VM.isBooted() && (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
    //TODO 異或操作,二者滿(mǎn)足一個(gè)條件即可rehash
    boolean switching = currentAltHashing ^ useAltHashing;
    if (switching) {
      // 更新hashseed的值
      hashSeed = useAltHashing ? sun.misc.Hashing.randomHashSeed(this) : 0;
    }
    return switching;
  }

4:HashMap在多線(xiàn)程環(huán)境下進(jìn)行put操作如何導(dǎo)致的死循環(huán)?

死循環(huán)產(chǎn)生時(shí)機(jī):

當(dāng)兩個(gè)線(xiàn)程同時(shí)需要進(jìn)行擴(kuò)容,而且對(duì)哈希表同一個(gè)桶(table[i])進(jìn)行擴(kuò)容時(shí)候,一個(gè)線(xiàn)程剛好確定e和next元素之后,線(xiàn)程被掛起。此時(shí)另一個(gè)線(xiàn)程得到cpu并順利對(duì)該桶完成轉(zhuǎn)移(需要要求被轉(zhuǎn)移之后的線(xiàn)程1中的e和next指的元素在新哈希表的同一個(gè)桶中,此時(shí)e和next被逆序了)。接著線(xiàn)程從掛起恢復(fù)回來(lái)時(shí)候就會(huì)陷入死循環(huán)中。參考:https://coolshell.cn/articles/9606.html

產(chǎn)生原因:主要由于并發(fā)操作,對(duì)用一個(gè)桶的兩個(gè)節(jié)點(diǎn)構(gòu)成了環(huán),導(dǎo)致對(duì)環(huán)進(jìn)行無(wú)法轉(zhuǎn)移完畢元素陷入死循環(huán)。

Java HashMap源碼及并發(fā)環(huán)境常見(jiàn)問(wèn)題解決

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:https://www.cnblogs.com/leodaxin/p/7708618.html

延伸 · 閱讀

精彩推薦
317
主站蜘蛛池模板: 久久经典国产视频 | 色678黄网站全部免费 | 正在播放91精 | 一级一片免费看 | 99爱视频在线观看 | 成人男男视频拍拍拍在线观看 | 亚洲最大久久 | chinesegv男男猛男无套 | 国产一区二区高清在线 | 欧美久久久一区二区三区 | 久久综合久久精品 | 久久综合婷婷香五月 | 亚洲午夜久久久精品一区二区三区 | 欧美视频一二区 | 欧美区在线| 看免费黄色大片 | 性少妇videosexfreexx入片 | 色综合久久久久久久久久久 | 久久免费激情视频 | 久久激情国产 | 天天干天天透 | 久久成人激情视频 | 国产精品爱久久久久久久 | 国产三级国产精品国产普男人 | 国产精品午夜一区 | 欧美精品网址 | 亚洲精中文字幕二区三区 | 精品中文字幕视频 | 久久成人视屏 | 成人午夜免费福利 | 亚洲黑人在线观看 | h视频在线免费观看 | h视频在线免费观看 | 成人三级视频在线观看 | 成人国产免费观看 | 免费观看一级黄色片 | 99爱精品在线 | 国产精品欧美久久久久一区二区 | 伊久在线 | 欧美一级在线免费 | 久久丝袜脚交足黄网站免费 |