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

相关推荐
石榴2 分钟前
NestJS 的请求到底经过了什么:装饰器、守卫、拦截器、管道与中间件如何配合
后端
Gopher_HBo9 分钟前
moby-client客户端
后端
杨运交33 分钟前
[055][调度模块]Spring动态任务调度框架的设计与实现
java·后端·spring
卷福同学2 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端
Csvn3 小时前
📊 SQL 入门 Day 11:CASE 表达式:SQL 里的 if-else 魔法
后端·sql
QQ_21696290963 小时前
Spring Boot 养老院管理系统:从入住、护理到费用结算的全流程实现(源码可领)
java·spring boot·后端
万少5 小时前
DeepSeek-V4-Flash 正式版上线了,但这 3 个坑我帮你提前踩了
前端·javascript·后端
明月_清风5 小时前
🚀 Palantir Foundry 本体论实战:当 Ontology 从"知识图谱"进化为"企业操作系统"
前端·后端
明月_清风5 小时前
从概念到代码:用 Ontology 构建你的第一个知识图谱
前端·后端
Python私教6 小时前
Django 6.1 邮件配置大改:旧项目如何平稳升级?
后端·python·django