concurrentHashMap面試題

面試題:面試

  1. ConcurrentHashMap有哪些構造函數?
  2. ConcurrentHashMap使用什麼技術來保證線程安全?
  3. ConcurrentHashMap的get方法是否要加鎖,爲何?
  4. ConcurrentHashMap迭代器是強一致性仍是弱一致性?HashMap呢?
  5. ConcurrentHashMap1.7和1.8的區別;

一、ConcurrentHashMap有哪些構造函數?數組

一共有五個,做用及代碼以下:安全

//無參構造函數
    public ConcurrentHashMap() { } //可傳初始容器大小的構造函數
    public ConcurrentHashMap(int initialCapacity) { if (initialCapacity < 0) throw new IllegalArgumentException(); int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1)); this.sizeCtl = cap; } //可傳入map的構造函數
    public ConcurrentHashMap(Map<? extends K, ? extends V> m) { this.sizeCtl = DEFAULT_CAPACITY; putAll(m); } //可設置閾值和初始容量
    public ConcurrentHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, 1); } //可設置初始容量和閾值和併發級別
    public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0) throw new IllegalArgumentException(); if (initialCapacity < concurrencyLevel)   // Use at least as many bins
            initialCapacity = concurrencyLevel;   // as estimated threads
        long size = (long)(1.0 + (long)initialCapacity / loadFactor); int cap = (size >= (long)MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int)size); this.sizeCtl = cap; }
View Code

 

二、ConcurrentHashMap使用什麼技術來保證線程安全?數據結構

 

jdk1.7:Segment+HashEntry來進行實現的;併發

jdk1.8:放棄了Segment臃腫的設計,採用Node+CAS+Synchronized來保證線程安全;ide

 

三、ConcurrentHashMap的get方法是否要加鎖,爲何?函數

不須要,get方法採用了unsafe方法,來保證線程安全。this

 

四、ConcurrentHashMap迭代器是強一致性仍是弱一致性?HashMap呢?spa

弱一致性,hashmap強一直性。線程

ConcurrentHashMap能夠支持在迭代過程當中,向map添加新元素,而HashMap則拋出了ConcurrentModificationException,

由於HashMap包含一個修改計數器,當你調用他的next()方法來獲取下一個元素時,迭代器將會用到這個計數器。

 

五、ConcurrentHashMap1.7和1.8的區別:

jdk1.8的實現下降鎖的粒度,jdk1.7鎖的粒度是基於Segment的,包含多個HashEntry,而jdk1.8鎖的粒度就是Node

數據結構:jdk1.7 Segment+HashEntry;jdk1.8 數組+鏈表+紅黑樹+CAS+synchronized

相關文章
相關標籤/搜索