如果讓你來做HashMap擴容,如何實現在不影響讀寫的情況下擴容?



1.了解HashMap的實現;如果一個面試者了解這一點,說明至少他關心過java提供的數據類型的實現,甚至極可能看過源碼,他應該不會是一個純粹的苦力
2.知道"不影響讀寫的情況下擴容"是什么含義,說明他在工作中了解多線程的相關知識
3.如果他能提到ConcurrentHashMap中的相關內容,說明他日常編程中有使用到concurrent包,可以繼續聊聊,否則他對多線程的使用可能非常初級
4.如果他能提出一些解決方案,即使不完整,也能看出他對類似CAS、分布式一致性等問題的了解程度


一、org.apache.commons.collections.FastHashMap

A customized implementation of java.util.HashMap designed to operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes. When operating in "fast" mode, read calls are non-synchronized and write calls perform the following steps:

  • Clone the existing collection
  • Perform the modification on the clone
  • Replace the existing collection with the (modified) clone
    public Object put(Object key, Object value) {
        if (fast) {
            synchronized (this) {
                HashMap temp = (HashMap) map.clone();
                Object result = temp.put(key, value);
                map = temp;
                return (result);
            }
        } else {
            synchronized (map) {
                return (map.put(key, value));
            }
        }
    }

 

 

二、io.netty.util.collection.IntObjectHashMap

區別並不僅僅在於int 換 Integer的那點空間,而是整個存儲結構和Hash沖突的解決方法都不一樣。

HashMap的結構是 Node[] table; Node 下面有Hash,Key,Value,Next四個屬性。

而IntObjectHashMap的結構是int[] keys 和 Object[] values.

在插入時,同樣把int先取模落桶,如果遇到沖突,則不采樣HashMap的鏈地址法,而是用開放地址法(線性探測法)index+1找下一個空桶,最后在keys[index],values[index]中分別記錄。在查找時也是先落桶,然后在key[index++]中逐個比較key。

所以,對比整個數據結構,省的不止是int vs Integer,還有每個Node的內容。

而性能嘛,IntObjectHashMap還是穩贏一點的,隨便測了幾種場景,耗時至少都有24ms vs 28ms的樣子,好的時候甚至快1/3。

 

三、ConcurrentHashMap

 

 

參考:

江南白衣:高性能下,map家族優化建議


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM