死磕java集合之ConcurrentSkipListSet源碼分析——Set大匯總

問題

(1)ConcurrentSkipListSet的底層是ConcurrentSkipListMap嗎?

漢陰網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián)公司,漢陰網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為漢陰成百上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站制作要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的漢陰做網(wǎng)站的公司定做!

(2)ConcurrentSkipListSet是線程安全的嗎?

(3)ConcurrentSkipListSet是有序的嗎?

(4)ConcurrentSkipListSet和之前講的Set有何不同?

簡介

ConcurrentSkipListSet底層是通過ConcurrentNavigableMap來實(shí)現(xiàn)的,它是一個(gè)有序的線程安全的集合。

源碼分析

它的源碼比較簡單,跟通過Map實(shí)現(xiàn)的Set基本是一致,只是多了一些取最近的元素的方法。

為了保持專欄的完整性,我還是貼一下源碼,最后會(huì)對(duì)Set的整個(gè)家族作一個(gè)對(duì)比,有興趣的可以直接拉到最下面。

// 實(shí)現(xiàn)了NavigableSet接口,并沒有所謂的ConcurrentNavigableSet接口
public class ConcurrentSkipListSet<E>
    extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable {

    private static final long serialVersionUID = -2479143111061671589L;

    // 存儲(chǔ)使用的map
    private final ConcurrentNavigableMap<E,Object> m;

    // 初始化
    public ConcurrentSkipListSet() {
        m = new ConcurrentSkipListMap<E,Object>();
    }

    // 傳入比較器
    public ConcurrentSkipListSet(Comparator<? super E> comparator) {
        m = new ConcurrentSkipListMap<E,Object>(comparator);
    }

    // 使用ConcurrentSkipListMap初始化map
    // 并將集合c中所有元素放入到map中
    public ConcurrentSkipListSet(Collection<? extends E> c) {
        m = new ConcurrentSkipListMap<E,Object>();
        addAll(c);
    }

    // 使用ConcurrentSkipListMap初始化map
    // 并將有序Set中所有元素放入到map中
    public ConcurrentSkipListSet(SortedSet<E> s) {
        m = new ConcurrentSkipListMap<E,Object>(s.comparator());
        addAll(s);
    }

    // ConcurrentSkipListSet類內(nèi)部返回子set時(shí)使用的
    ConcurrentSkipListSet(ConcurrentNavigableMap<E,Object> m) {
        this.m = m;
    }

    // 克隆方法
    public ConcurrentSkipListSet<E> clone() {
        try {
            @SuppressWarnings("unchecked")
            ConcurrentSkipListSet<E> clone =
                (ConcurrentSkipListSet<E>) super.clone();
            clone.setMap(new ConcurrentSkipListMap<E,Object>(m));
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }

    /* ---------------- Set operations -------------- */
    // 返回元素個(gè)數(shù)
    public int size() {
        return m.size();
    }

    // 檢查是否為空
    public boolean isEmpty() {
        return m.isEmpty();
    }

    // 檢查是否包含某個(gè)元素
    public boolean contains(Object o) {
        return m.containsKey(o);
    }

    // 添加一個(gè)元素
    // 調(diào)用map的putIfAbsent()方法
    public boolean add(E e) {
        return m.putIfAbsent(e, Boolean.TRUE) == null;
    }

    // 移除一個(gè)元素
    public boolean remove(Object o) {
        return m.remove(o, Boolean.TRUE);
    }

    // 清空所有元素
    public void clear() {
        m.clear();
    }

    // 迭代器
    public Iterator<E> iterator() {
        return m.navigableKeySet().iterator();
    }

    // 降序迭代器
    public Iterator<E> descendingIterator() {
        return m.descendingKeySet().iterator();
    }

    /* ---------------- AbstractSet Overrides -------------- */
    // 比較相等方法
    public boolean equals(Object o) {
        // Override AbstractSet version to avoid calling size()
        if (o == this)
            return true;
        if (!(o instanceof Set))
            return false;
        Collection<?> c = (Collection<?>) o;
        try {
            // 這里是通過兩次兩層for循環(huán)來比較
            // 這里是有很大優(yōu)化空間的,參考上篇文章CopyOnWriteArraySet中的彩蛋
            return containsAll(c) && c.containsAll(this);
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }
    }

    // 移除集合c中所有元素
    public boolean removeAll(Collection<?> c) {
        // Override AbstractSet version to avoid unnecessary call to size()
        boolean modified = false;
        for (Object e : c)
            if (remove(e))
                modified = true;
        return modified;
    }

    /* ---------------- Relational operations -------------- */

    // 小于e的最大元素
    public E lower(E e) {
        return m.lowerKey(e);
    }

    // 小于等于e的最大元素
    public E floor(E e) {
        return m.floorKey(e);
    }

    // 大于等于e的最小元素
    public E ceiling(E e) {
        return m.ceilingKey(e);
    }

    // 大于e的最小元素
    public E higher(E e) {
        return m.higherKey(e);
    }

    // 彈出最小的元素
    public E pollFirst() {
        Map.Entry<E,Object> e = m.pollFirstEntry();
        return (e == null) ? null : e.getKey();
    }

    // 彈出最大的元素
    public E pollLast() {
        Map.Entry<E,Object> e = m.pollLastEntry();
        return (e == null) ? null : e.getKey();
    }

    /* ---------------- SortedSet operations -------------- */

    // 取比較器
    public Comparator<? super E> comparator() {
        return m.comparator();
    }

    // 最小的元素
    public E first() {
        return m.firstKey();
    }

    // 最大的元素
    public E last() {
        return m.lastKey();
    }

    // 取兩個(gè)元素之間的子set
    public NavigableSet<E> subSet(E fromElement,
                                  boolean fromInclusive,
                                  E toElement,
                                  boolean toInclusive) {
        return new ConcurrentSkipListSet<E>
            (m.subMap(fromElement, fromInclusive,
                      toElement,   toInclusive));
    }

    // 取頭子set
    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
        return new ConcurrentSkipListSet<E>(m.headMap(toElement, inclusive));
    }

    // 取尾子set
    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
        return new ConcurrentSkipListSet<E>(m.tailMap(fromElement, inclusive));
    }

    // 取子set,包含from,不包含to
    public NavigableSet<E> subSet(E fromElement, E toElement) {
        return subSet(fromElement, true, toElement, false);
    }

    // 取頭子set,不包含to
    public NavigableSet<E> headSet(E toElement) {
        return headSet(toElement, false);
    }

    // 取尾子set,包含from
    public NavigableSet<E> tailSet(E fromElement) {
        return tailSet(fromElement, true);
    }

    // 降序set
    public NavigableSet<E> descendingSet() {
        return new ConcurrentSkipListSet<E>(m.descendingMap());
    }

    // 可分割的迭代器
    @SuppressWarnings("unchecked")
    public Spliterator<E> spliterator() {
        if (m instanceof ConcurrentSkipListMap)
            return ((ConcurrentSkipListMap<E,?>)m).keySpliterator();
        else
            return (Spliterator<E>)((ConcurrentSkipListMap.SubMap<E,?>)m).keyIterator();
    }

    // 原子更新map,給clone方法使用
    private void setMap(ConcurrentNavigableMap<E,Object> map) {
        UNSAFE.putObjectVolatile(this, mapOffset, map);
    }

    // 原子操作相關(guān)內(nèi)容
    private static final sun.misc.Unsafe UNSAFE;
    private static final long mapOffset;
    static {
        try {
            UNSAFE = sun.misc.Unsafe.getUnsafe();
            Class<?> k = ConcurrentSkipListSet.class;
            mapOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("m"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }
}

可以看到,ConcurrentSkipListSet基本上都是使用ConcurrentSkipListMap實(shí)現(xiàn)的,雖然取子set部分是使用ConcurrentSkipListMap中的內(nèi)部類,但是這些內(nèi)部類其實(shí)也是和ConcurrentSkipListMap相關(guān)的,它們返回ConcurrentSkipListMap的一部分?jǐn)?shù)據(jù)。

另外,這里的equals()方法實(shí)現(xiàn)的相當(dāng)敷衍,有很大的優(yōu)化空間,作者這樣實(shí)現(xiàn),應(yīng)該也是知道幾乎沒有人來調(diào)用equals()方法吧。

總結(jié)

(1)ConcurrentSkipListSet底層是使用ConcurrentNavigableMap實(shí)現(xiàn)的;

(2)ConcurrentSkipListSet有序的,基于元素的自然排序或者通過比較器確定的順序;

(3)ConcurrentSkipListSet是線程安全的;

彩蛋

Set大匯總:

Set有序性線程安全底層實(shí)現(xiàn)關(guān)鍵接口特點(diǎn)
HashSetHashMap簡單
LinkedHashSetLinkedHashMap插入順序
TreeSetNavigableMapNavigableSet自然順序
CopyOnWriteArraySetCopyOnWriteArrayList插入順序,讀寫分離
ConcurrentSkipListSetConcurrentNavigableMapNavigableSet自然順序

從中我們可以發(fā)現(xiàn)一些規(guī)律:

(1)除了HashSet其它Set都是有序的;

(2)實(shí)現(xiàn)了NavigableSet或者SortedSet接口的都是自然順序的;

(3)使用并發(fā)安全的集合實(shí)現(xiàn)的Set也是并發(fā)安全的;

(4)TreeSet雖然不是全部都是使用的TreeMap實(shí)現(xiàn)的,但其實(shí)都是跟TreeMap相關(guān)的(TreeMap的子Map中組合了TreeMap);

(5)ConcurrentSkipListSet雖然不是全部都是使用的ConcurrentSkipListMap實(shí)現(xiàn)的,但其實(shí)都是跟ConcurrentSkipListMap相關(guān)的(ConcurrentSkipListeMap的子Map中組合了ConcurrentSkipListMap);

新聞標(biāo)題:死磕java集合之ConcurrentSkipListSet源碼分析——Set大匯總
網(wǎng)址分享:http://muchs.cn/article18/ihdjdp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊(cè)、網(wǎng)站設(shè)計(jì)公司、服務(wù)器托管網(wǎng)站排名、網(wǎng)站制作、微信公眾號(hào)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)