日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区

您的位置:首頁技術文章
文章詳情頁

Java HashMap源碼及并發環境常見問題解決

瀏覽:23日期:2022-08-24 16:35:35

HashMap源碼簡單分析:

1 一切需要從HashMap屬性字段說起:

/** 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.  * 默認的負載因子,當map的size>=負載因子*capacity時候并且插入元素時候的table[i]!=null進行擴容 * 擴容判斷邏輯:java.util.HashMap#addEntry函數中 * */ 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. 擴容的閾值 = capacity * 負載因子 int threshold; /** * The load factor for the hash table. 負載因子,默認是0.75,可以在創建HashMap時候通過構造函數指定 * * @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). * 修改次數:例如進行rehash或者返回hashMap視圖時候如果發生修改可以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時候判斷的一個閾值 */ static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;

2: 接下來查看一下HashMap的put方法:

/** * 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 存儲到table[0]位置 return putForNullKey(value); int hash = hash(key); //計算hash值 int i = indexFor(hash, table.length);//計算entry在table中的位置 //for循環邏輯用于修改key對應的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;//如果是更新返回舊值 } } //修改次數++ modCount++; //添加元素到哈希表中 addEntry(hash, key, value, i); // 如果是添加元素則返回null return null; }

3 put中調用的inflateTable方法:

/** * Inflates the table. */ private void inflateTable(int toSize) { // Find a power of 2 >= toSize //計算大于等于toSize的最小的2的整數次冪的值 int capacity = roundUpToPowerOf2(toSize); //計算擴容閾值 threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); //初始化哈希表 table = new Entry[capacity]; //更新一下rehash的判斷條件,便于以后判斷是否rehash initHashSeedAsNeeded(capacity); }

4 put方法中調用的indexFor方法:

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

5 put方法中調用的addEntry方法:

/** * 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) { //判斷是否擴容,只有size大于等于閾值而且當前插入table[i]!=null(就是able[i]已經被占用則擴容) if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * table.length); hash = (null != key) ? hash(key) : 0; //如果需要擴容的話則需要更新再次重新計算哈希表位置 bucketIndex = indexFor(hash, table.length); } //將值插入到哈希表中 createEntry(hash, key, value, bucketIndex); }

6 addEntry方法中調用的createEntry方法:

/** * 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]; // 鏈表的頭插入方式進行插入,插入邏輯在Entry的構造器中。然后將新節點存儲到 table[bucketIndex]中 table[bucketIndex] = new Entry<>(hash, key, value, e); size++;//更新size即可 }

Entry構造器:

/** * * @param h hash值 * @param k key * @param v value * @param n 原始鏈表 */ Entry(int h, K k, V v, Entry<K,V> n) { value = v; //將原始鏈表接該節點后面 next = n; key = k; hash = h; }

7 接下來看一下java.util.HashMap#addEntry擴容機制:

當進行擴容時候需要重新計算哈希值和在哈希表中的位置。

void addEntry(int hash, K key, V value, int bucketIndex) { //滿足擴容條件進行擴容 if ((size >= threshold) && (null != table[bucketIndex])) { //擴容,2倍進行擴容 resize(2 * table.length); //重新計算哈數值 hash = (null != key) ? hash(key) : 0; //重新計算哈希表中的位置 bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex); }

接下來看一下java.util.HashMap#resize方法:

/** * 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) {//判斷當前old容量是否最最大容量,是的話更新閾值 threshold = Integer.MAX_VALUE; return; } //創建新的表 Entry[] newTable = new Entry[newCapacity]; //元素轉移,根據initHashSeedAsNeeded結果判斷是否進行rehash transfer(newTable, initHashSeedAsNeeded(newCapacity)); // 新表賦給table table = newTable; //更新閾值 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); }

關于HashMap在并發情況下的常見問題,其實在多線程環境下使用HashMap本來就是有風險錯誤的,但是一般面試卻喜歡這么問,下面列舉一下自己印象中的常見問題:

1:在進行擴容時候,其他線程是否可以進行進行插入操作(多線程環境下可能會導致HashMap進入死循環,此處暫不考慮)?

答:首先HashMap就不是一個線程安全的容器,所以在多線程環境下使用就是錯誤的。其次在擴容時候可以進行插入的,但是不安全。例如:

當主線程在調用transfer方法進行復制元素:

/** * 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; } } }

此時另一個線程在添加新元素是可以的,新元素添加到table中。如果子線程需要擴容的話可以進行擴容,然后將新容器賦給table。而此時主線程轉移元素的工作就是將table中元素轉移到newTable中。注意main線程的transfer方法:

如果main線程剛進入transfer方法時候newTable大小是32的話,由于子線程的添加操作導致table此時元素如果有128的話。則128個元素就會存儲到大小為32的newTable中(此處不會擴容)。這就會導致HashMap性能下降!!!

可以使用多線程環境進行debug查看即可確定(推薦Idea的debug,的確強大,尤其是Evaluate Expression功能)。

2:進行擴容時候元素是否需要重新Hash?

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

/** * 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); }

然后進行轉移元素:

/** * Transfers all entries from current table to newTable. */ void transfer(Entry[] newTable, boolean rehash) { int newCapacity = newTable.length; //多線程環境下,如果其他線程導致table快速擴大。newTable在此處無法擴容會導致性能下降。但是如果后面有再次調用put方法的話可以再次觸發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?

/** * 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: 當map的capacity容量大于這個值的時候并滿足其他條件時候進行重新hash boolean useAltHashing = sun.misc.VM.isBooted() && (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD); //TODO 異或操作,二者滿足一個條件即可rehash boolean switching = currentAltHashing ^ useAltHashing; if (switching) { // 更新hashseed的值 hashSeed = useAltHashing ? sun.misc.Hashing.randomHashSeed(this) : 0; } return switching; }

4:HashMap在多線程環境下進行put操作如何導致的死循環?

死循環產生時機:

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

產生原因:主要由于并發操作,對用一個桶的兩個節點構成了環,導致對環進行無法轉移完畢元素陷入死循環。

Java HashMap源碼及并發環境常見問題解決

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区
欧美不卡视频| 久久久久久免费视频| 91亚洲国产成人久久精品| 国产福利亚洲| 国产精品第十页| 欧美激情aⅴ一区二区三区 | 日韩美女国产精品| 高清av一区| 综合日韩av| 久久视频一区| 日韩在线观看中文字幕| 97久久亚洲| 日本成人在线视频网站| 亚洲最新av| 国产免费播放一区二区| 久久成人高清| 正在播放日韩精品| 午夜精品免费| 欧美一级全黄| 日韩啪啪电影网| 视频一区二区欧美| 国产美女久久| 久久久久99| 日本不卡视频在线| 日本精品黄色| 亚洲狼人精品一区二区三区| 在线视频亚洲欧美中文| 蜜臀久久99精品久久一区二区| 午夜久久福利| 国产精品久久久网站| 日韩欧美另类一区二区| 国产一区成人| 福利片在线一区二区| 爽爽淫人综合网网站| 国产成人在线中文字幕| 亚洲毛片网站| 久久蜜桃精品| 久久要要av| 麻豆91小视频| 免费在线观看不卡| 欧美午夜精彩| 精品视频在线你懂得| 亚洲精品麻豆| 亚洲电影有码| 精品国产午夜肉伦伦影院| 亚洲免费专区| 亚洲黄页一区| 99精品在线观看| 岛国av免费在线观看| 国产精品亚洲综合色区韩国| 亚洲一区导航| 亚洲五月综合| 蜜臀av亚洲一区中文字幕| 女人av一区| 在线日韩电影| 欧美1区免费| 欧美一级精品| 亚洲高清久久| 亚洲一区久久| 色婷婷亚洲mv天堂mv在影片| 欧美激情视频一区二区三区在线播放| 欧美日韩免费观看一区=区三区| 麻豆理论在线观看| 久久不卡日韩美女| 国产精品网站在线看| 日韩va亚洲va欧美va久久| 蜜桃av一区二区三区电影| 精品1区2区3区4区| 午夜宅男久久久| 亚洲伊人影院| 日韩精选在线| 久久不见久久见免费视频7| 国产免费av国片精品草莓男男 | 婷婷精品视频| 91精品99| 亚洲色图国产| 国产精品三p一区二区| 欧美亚洲二区| 成人在线超碰| 欧美日韩少妇| 久久国产日韩欧美精品| 欧美1区二区| 激情综合自拍| 蜜桃视频一区二区| 久久精品一区二区三区中文字幕| 国产美女视频一区二区| 人在线成免费视频| 国产手机视频一区二区| 麻豆精品蜜桃视频网站| 高清久久一区| 亚洲精品护士| 日韩在线视频精品| 视频一区二区中文字幕| 精品中文字幕一区二区三区四区| 99久久久久久中文字幕一区| 亚洲精选91| 成人免费网站www网站高清| 亚洲欧美在线综合| 国产色播av在线| 亚洲精品综合| 国产一区二区三区探花| 午夜久久一区| 欧美激情一区| 亚洲精品欧美| 亚洲欧美日韩高清在线| 免费亚洲一区| 综合色一区二区| 免费欧美一区| 欧美天堂视频| 精品免费视频| 国产精品三级| 日韩有吗在线观看| 91精品精品| 精品一区二区三区视频在线播放| 久久午夜影视| 亚洲日本免费电影| 日本欧美一区二区| 麻豆视频观看网址久久| 日韩午夜在线| 伊人影院久久| 久久久久久久久久久9不雅视频| 国产精品密蕾丝视频下载| 亚洲午夜国产成人| 亚洲免费影视| 免费精品视频| 日韩午夜电影| 一区二区国产精品| 蜜桃视频一区二区| 视频一区日韩精品| 日本精品另类| 美美哒免费高清在线观看视频一区二区| 伊人网在线播放| 秋霞影院一区二区三区| 久久久夜夜夜| 中文亚洲免费| 免费国产自线拍一欧美视频| 中文字幕一区二区av| 日韩在线观看一区二区三区| 国产亚洲精品美女久久久久久久久久| 日韩av影院| 高清日韩中文字幕| 精品欧美久久| 日本不卡一区二区三区| 国产精品一区二区免费福利视频| 国产欧美日韩精品高清二区综合区| 青草国产精品| 久久亚洲黄色| 日本精品不卡| 美女精品在线观看| 国产欧美日韩在线一区二区| 久久av超碰| 999久久久国产精品| 日本成人手机在线| 久久字幕精品一区| 成人av二区| 国产精品主播在线观看| 福利欧美精品在线| 老鸭窝毛片一区二区三区| 欧美三区不卡| 在线日韩视频| 日韩av午夜在线观看| 日韩国产专区| 亚洲91网站| 久久在线免费| 国产精品网站在线看| 国产亚洲综合精品| 天堂√中文最新版在线| 日韩精品中文字幕吗一区二区| 日韩一区二区中文| 国产精品久久免费视频| 国产精品日韩欧美一区| 国产videos久久| 深夜福利一区| 亚洲精品午夜av福利久久蜜桃| 国产日韩高清一区二区三区在线| 国产在线一区不卡| 人人爽香蕉精品| 亚洲a一区二区三区| 久久永久免费| 国产午夜一区| 日韩精品中文字幕吗一区二区| 日韩午夜av| 国产成人精选| 婷婷成人在线| 亚洲精品成人图区| 欧美激情久久久久久久久久久| 免费在线观看不卡| 米奇777超碰欧美日韩亚洲| 中文字幕人成乱码在线观看 | 久久九九电影| 超碰在线99| 精品一区二区三区视频在线播放| 国产欧美一区二区色老头| 日韩国产欧美在线视频| 日本va欧美va瓶| 免费观看久久久4p| 一区二区三区国产在线| 中文视频一区| 欧美日一区二区在线观看| 88久久精品|