Vector 源碼分析

Vector 簡(jiǎn)介

Vector 和 ArrayList 類似,頂級(jí)父類為 Collection,區(qū)別于 ArrayList 的重要一點(diǎn),Vector 集合類為線程安全類,而本篇文章也將深入去解析為什么 Vector 可以做到線程安全。

vector 結(jié)構(gòu)圖

vector.png

Vector 源碼解析

因?yàn)楹?ArrayList 使用類似,這里直接對(duì) Vector 源碼的相關(guān)增刪改查操作進(jìn)行分析;

ArrayList 相關(guān)源碼分析
http://www.itdecent.cn/p/0d1815792651

Vector 的構(gòu)造方法

public Vector(int initialCapacity) {
    this(initialCapacity, 0);
}


public Vector() {
    this(10);
}


public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];
    this.capacityIncrement = capacityIncrement;
}

Vector 的構(gòu)造方法初始化容量為 10 的數(shù)組,同時(shí)初始化變量 capacityIncrement 為 0;

Vector 的 add 方法

public synchronized boolean add(E e) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);// 擴(kuò)容
    elementData[elementCount++] = e;
    return true;
}

private void ensureCapacityHelper(int minCapacity) {
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

針對(duì) add 方法 synchronized 加鎖機(jī)制,當(dāng)多線程進(jìn)行訪問(wèn)的時(shí)候先要獲取鎖才能操作;ensureCapacityHelper 進(jìn)行判斷是否擴(kuò)容,elementCount 為當(dāng)前存入的數(shù)據(jù)數(shù)量,當(dāng)下一位將要大于數(shù)組容量的時(shí)候就要擴(kuò)容處理。和 ArrayList 不同的是,這里進(jìn)行 2n 倍擴(kuò)容;

Vector 的 remove 方法

public synchronized E remove(int index) {
    modCount++;
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);
    E oldValue = elementData(index);

    int numMoved = elementCount - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--elementCount] = null; // Let gc do its work

    return oldValue;
}

synchronized 加鎖保證同步性,刪除之后數(shù)組后面位數(shù)進(jìn)行前移動(dòng),原數(shù)組最后一位置空;同時(shí)可以看到每次增刪操作都會(huì)對(duì) modCount 自增處理;

Vector 的 get 和 set 方法

public synchronized E get(int index) {
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);

    return elementData(index);
}



public synchronized E set(int index, E element) {
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);

    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}

synchronized 保證同步性;

看完 Vector 的增刪改查操作方法可以看到 Vector 主要通過(guò) synchronized 加鎖機(jī)制保證了數(shù)據(jù)的同步;

Vector的數(shù)據(jù)遍歷

public synchronized Iterator<E> iterator() {
    return new Itr();
}

private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    public boolean hasNext() {
        // Racy but within spec, since modifications are checked
        // within or after synchronization in next/previous
        return cursor != elementCount;
    }

    public E next() {
        synchronized (Vector.this) {
            checkForComodification();
            int i = cursor;
            if (i >= elementCount)
                throw new NoSuchElementException();
            cursor = i + 1;
            return elementData(lastRet = i);
        }
    }

    public void remove() {
        if (lastRet == -1)
            throw new IllegalStateException();
        synchronized (Vector.this) {
            checkForComodification();
            Vector.this.remove(lastRet);
            expectedModCount = modCount;
        }
        cursor = lastRet;
        lastRet = -1;
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

對(duì)比 ArrayList 中的 Itertor 迭代器:

 private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    public boolean hasNext() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

同樣是通過(guò) synchronized 加鎖的方式實(shí)現(xiàn)數(shù)據(jù)的同步;

至此,可以得出結(jié)論,Vector 主要是在 ArrayList 的基礎(chǔ)之上針對(duì)數(shù)據(jù)的操作進(jìn)行加鎖保護(hù),從而實(shí)現(xiàn)數(shù)據(jù)的同步性;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容