List并发实现-Vector

全路径名:java.util.Vector

类的定义如下:

js 复制代码
/**
 ..
* @since JDK1.0
*/
public class Vector<E> 
    extends AbstractList<E> 
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    ...
    protected Object[] elementData;
    ...     
}

Vector 类实现了List接口,内部使用了数组,JDK1.0 引入。

看一下List接口常用的 add()、remove() 方法的实现

js 复制代码
public synchronized boolean add(E e) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = e;
    return true;
}
js 复制代码
public synchronized E set(int index, E element) {
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);

    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}
js 复制代码
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 可以看出,使用了同步代码块机制,每次只能有一个线程进行操作。其他方法可以自己查看源码,都是采用 synchronized 方式实现的。

还需要关心的是 iterator() 方法。迭代时会不会抛出 ConcurrentModificationException 异常。看一下它的实现方式:

js 复制代码
...
public synchronized Iterator<E> iterator() {
        return new Itr();
}

private class Itr implements Iterator<E> {
    ...
    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);
            }
    }
    ...
}
...

从 synchronized (Vector.this) 可以看出使用了对象锁,与前面的方式一样。

简单介绍下Vector的实现方式,synchronized 的使用方法不做过多解释。

相关推荐
葫芦和十三3 分钟前
图解 MongoDB 06|模式演进:无 schema 是优势还是债
后端·mongodb·agent
葫芦和十三8 小时前
图解 MongoDB 05|文档模型设计:内嵌 vs 引用,反范式不是免费午餐
后端·mongodb·agent
不能放弃治疗11 小时前
单 Agent 实现模式
后端
IT_陈寒13 小时前
Redis内存爆了,原来我漏掉了这个致命配置
前端·人工智能·后端
fliter14 小时前
最后一块拼图:用 bitvec 构造 IPv4 包,真正做出自己的 Ping
后端
fliter15 小时前
用 Rust 解析并生成 ICMP 包:checksum、nom 与 cookie-factory
后端
蝎子莱莱爱打怪15 小时前
XZLL-IM干货系列 03|消息 ID 设计:一个 UUID 搞不定的事,我用两个 ID 解决了
后端·面试·开源
fliter15 小时前
从 panic 到 Result:用 Rust 重新整理一个 ping 项目的错误处理
后端
森蓝情丶16 小时前
我给 AI 搭了个法庭:一个前端仔的 LangGraph 实战全记录
前端·后端
JensCS猿16 小时前
从 Spring Boot 回看 SSM 框架:手动挡与自动挡的驾驶哲学
后端