ConcurrentSkipListSet - 秒懂



說明:閱讀本文之前,請先掌握本文前置知識: 跳表 核心原理 圖解,以及ConcurrentSkipListMap - 秒懂

JUC 高並發工具類(3文章)與高並發容器類(N文章) :


1 ConcurrentSkipListSet簡介

ConcurrentSkipListSet,是J.U.C新增的一個集合工具類,顧名思義,它是一種SET類型。

SET類型,在數學上稱為“集合”,具有互異性、無序性的特點,也就是說SET中的任意兩個元素均不相同(即不包含重復元素),且元素是無序的。

JDK提供的默認SET實現——HashSet,其實就是采用“組合”的方式——內部引用了一個HashMap對象,以此實現SET的功能。

ConcurrentSkipListSet與ConcurrentSkipListMap的關系,與SET與HashMap的關系類似,就是采用“組合”的方式: ConcurrentSkipListSet組合了一個ConcurrentSkipListMap,將元素作為 ConcurrentSkipListMap的key存放。

2 ConcurrentSkipListSet原理

2.1 ConcurrentSkipListSet的類繼承圖

我們來看下ConcurrentSkipListSet的類繼承圖:

在這里插入圖片描述

2.2 內部結構

ConcurrentSkipListSet的數據結構,如下圖所示:

在這里插入圖片描述

說明:

(01) ConcurrentSkipListSet繼承於AbstractSet。因此,它本質上是一個集合。

(02) ConcurrentSkipListSet實現了NavigableSet接口。因此,ConcurrentSkipListSet是一個有序的集合。

(03) ConcurrentSkipListSet是通過組合ConcurrentSkipListMap實現的。它包含一個ConcurrentNavigableMap對象m,而m對象實際上是ConcurrentNavigableMap的實現類ConcurrentSkipListMap的實例。ConcurrentSkipListMap中的元素是key-value鍵值對;而ConcurrentSkipListSet是集合,它只用到了ConcurrentSkipListMap中的key!

2.3 構造器

ConcurrentSkipListSet的實現非常簡單,其內部引用了一個ConcurrentSkipListMap對象,所有API方法均委托ConcurrentSkipListMap對象完成:

public class ConcurrentSkipListSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable {

    /**
     * The underlying map. Uses Boolean.TRUE as value for each
     * element.  This field is declared final for the sake of thread
     * safety, which entails some ugliness in clone().
     */
    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);
    }

    public ConcurrentSkipListSet(Collection<? extends E> c) {
        m = new ConcurrentSkipListMap<E, Object>();
        addAll(c);
    }

    public ConcurrentSkipListSet(SortedSet<E> s) {
        m = new ConcurrentSkipListMap<E, Object>(s.comparator());
        addAll(s);
    }

    ConcurrentSkipListSet(ConcurrentNavigableMap<E, Object> m) {
        this.m = m;
    }
    
    // ...
}

從上述代碼可以看出,ConcurrentSkipListSet在構造時創建了一個ConcurrentSkipListMap對象,並由字段m引用,所以其實ConcurrentSkipListSet就是一種跳表類型的數據結構,其平均增刪改查的時間復雜度均為O(logn)。

2.4 核心方法

我們來看下ConcurrentSkipListSet是如何實現API方法的:


public int size() {
    return m.size();
}

public boolean isEmpty() {
    return m.isEmpty();
}

public boolean contains(Object o) {
    return m.containsKey(o);
}


public boolean add(E e) {
    return m.putIfAbsent(e, Boolean.TRUE) == null;
}

public boolean remove(Object o) {
    return m.remove(o, Boolean.TRUE);
}

public void clear() {
    m.clear();
}
 
//...

從上述代碼可以看出,所有操作均是委托ConcurrentSkipListMap對象完成的。重點看下add方法:

public boolean add(E e) {

​ return m.putIfAbsent(e, Boolean.TRUE) == null;

}

ConcurrentSkipListMap對鍵值對的要求是均不能為null,所以ConcurrentSkipListSet在插入元素的時候,用一個Boolean.TRUE對象(相當於一個值為true的Boolean型對象)作為value,同時putIfAbsent可以保證不會存在相同的Key。

所以,最終跳表中的所有Node結點的Key均不會相同,且值都是Boolean.True

3 ConcurrentSkipListSet適用場景

ConcurrentSkipListSet是線程安全的有序的集合,適用於高並發的場景。

ConcurrentSkipListSet和TreeSet

ConcurrentSkipListSet和TreeSet,它們雖然都是有序的集合。但是,第一,它們的線程安全機制不同,TreeSet是非線程安全的,而ConcurrentSkipListSet是線程安全的。第二,ConcurrentSkipListSet是通過ConcurrentSkipListMap實現的,而TreeSet是通過TreeMap實現的。

4 使用例子

import java.util.*;
import java.util.concurrent.*;

/*
 *   ConcurrentSkipListSet是“線程安全”的集合,而TreeSet是非線程安全的。
 *
 *   下面是“多個線程同時操作並且遍歷集合set”的示例
 *   (01) 當set是ConcurrentSkipListSet對象時,程序能正常運行。
 *   (02) 當set是TreeSet對象時,程序會產生ConcurrentModificationException異常。
 *
 * @author skywang
 */
public class ConcurrentSkipListSetDemo1 {

    // TODO: set是TreeSet對象時,程序會出錯。
    //private static Set<String> set = new TreeSet<String>();
    private static Set<String> set = new ConcurrentSkipListSet<String>();
    public static void main(String[] args) {

        // 同時啟動兩個線程對set進行操作!
        new MyThread("a").start();
        new MyThread("b").start();
    }

    private static void printAll() {
        String value = null;
        Iterator iter = set.iterator();
        while(iter.hasNext()) {
            value = (String)iter.next();
            System.out.print(value+", ");
        }
        System.out.println();
    }

    private static class MyThread extends Thread {
        MyThread(String name) {
            super(name);
        }
        @Override
        public void run() {
                int i = 0;
            while (i++ < 10) {
                // “線程名” + "序號"
                String val = Thread.currentThread().getName() + (i%6);
                set.add(val);
                // 通過“Iterator”遍歷set。
                printAll();
            }
        }
    }
}

運行程序,結果如下:

a1, b1, 
a1, a1, a2, b1, 
b1, a1, a2, a3, b1,

a1, a2, a3, a1, a4, b1, b2, 
a2, a1, a2, a3, a4, a5, b1, b2, 
a3, a0, a4, a5, a1, b1, a2, b2, 
a3, a0, a4, a1, a5, a2, b1, a3, b2, a4, b3, 
a5, a0, b1, a1, b2, a2, b3, 
a3, a0, a4, a1, a5, a2, b1, a3, b2, a4, b3, a5, b4, 
b1, a0, b2, a1, b3, a2, b4, 
a3, a0, a4, a1, a5, a2, b1, a3, b2, a4, b3, a5, b4, b1, b5, 
b2, a0, a1, a2, a3, a4, a5, b3, b1, b4, b2, b5, 
b3, a0, b4, a1, b5, 
a2, a0, a3, a1, a4, a2, a5, a3, b0, a4, b1, a5, b2, b0, b3, b1, b4, b2, b5, b3, 
b4, a0, b5, 
a1, a2, a3, a4, a5, b0, b1, b2, b3, b4, b5, 
a0, a1, a2, a3, a4, a5, b0, b1, b2, b3, b4, b5, 
a0, a1, a2, a3, a4, a5, b0, b1, b2, b3, b4, b5, 
a0, a1, a2, a3, a4, a5, b0, b1, b2, b3, b4, b5,

回到◀瘋狂創客圈

瘋狂創客圈 - Java高並發研習社群,為大家開啟大廠之門


免責聲明!

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



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