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 的使用方法不做过多解释。

相关推荐
2601_9537208210 小时前
【计算机毕业设计】基于Vue与Spring Boot的高校兼职信息服务平台设计与实现
spring boot·后端·课程设计
再吃一根胡萝卜11 小时前
用 Rust 写一个桌面悬浮图标:为什么它比 Python 更适合 AI 桌面工具?
后端
IT_陈寒12 小时前
Vue的computed属性把我坑惨了,原来我一直用错姿势
前端·人工智能·后端
evans在进步13 小时前
Spring Boot 核心机制详解:可执行 JAR、CORS、静态资源与配置绑定
spring boot·后端·jar
Sayuanni%313 小时前
SpringBoot 从注解到源码:核心知识点总结
java·spring boot·后端
陈随易14 小时前
Bun v1.4 更新总结:把浏览器、图片、定时任务和工程工具都装进一个运行时
前端·后端·程序员
人间凡尔赛14 小时前
2026 后端架构三驾马车:Wasm 容器上 K8s、存算分离与 AI 原生
后端·云原生·架构
凤山老林15 小时前
动态 i18n 体系落地:Spring Boot 多租户热加载与前后端协同实践
java·spring boot·后端·i18n
东风破_15 小时前
TypeScript 高级类型进阶:keyof、Exclude、Record 与类型组合思想
前端·后端·typescript
凤山老林15 小时前
数据库读写分离与动态路由实战:Spring Boot + ShardingSphere-JDBC 生产配置
数据库·spring boot·后端·分库分表·sharding-jdbc