JUC_併發映射

ConcurrentMap

ConcurrentMap是java1.5提供的一套應對高併發的映射機制,其數據結構是數組+鏈表
    主要特點:
    1.因爲其應用了分桶/斷鎖讀寫鎖機制以及無鎖算法CAS,在併發的情況下還能保住線程的安全。
    2.當桶中的節點個數大於8個,將桶中的鏈表轉爲紅黑樹。節點個數小於7個時,轉爲鏈表。
    3.桶的默認容量是16,加載因子爲0.75,默認擴容是增加一倍的桶數。且最多允許存在2302 ^ {30}個桶。

ConcurrentMap是一個接口,其直接實現類有:ConcurrentHashMap, ConcurrentSkipListMap
在這裏插入圖片描述
ConcurrentHashMap在創建時,提供了可以創建指定初始容量的構造方法:

 /**
     * Creates a new, empty map with an initial table size
     * accommodating the specified number of elements without the need
     * to dynamically resize.
     *
     * @param initialCapacity The implementation performs internal
     * sizing to accommodate this many elements.
     * @throws IllegalArgumentException if the initial capacity of
     * elements is negative
     */
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;
    }

但是通過源碼分析得知,並不是你簡單粗暴地你給多少容量它就設置多少容量。官方解釋是這樣的:

Parameters: initialCapacity - The implementation performs internal
sizing to accommodate this many elements.

大概的意思是會進行內部的調整以容納元素。通過計算,它總會將你設置的容量大小調整爲2的某次方(2n2 ^ {n})形式。比如,給定19,最終計算的實際容量將會是32(252 ^ {5})。
其中集體計算細節感興趣的可以深入研究。

另外一個ConcurrentSkipListMap實現類,數據結構是基於跳躍表實現的,可以極大提升數據的查詢速度,適用於查詢多,增刪少的場景。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章