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

相关推荐
陈随易1 小时前
在Finch用了62亿词元,我认为这是新一代Agent工具之神
前端·人工智能·后端
wing982 小时前
从codex转战workbuddy使用一周的感受
前端·人工智能·后端
EatFan2 小时前
Java接入支付宝 JSAPI 支付保姆教程(二):流程讲解与前后端代码讲解
前端·spring boot·后端·微信小程序·小程序·uni-app
步行cgn3 小时前
Spring 报错:No bean class specified on bean definition 的原因与解决
java·后端·spring
凤山老林3 小时前
Spring Boot 整合 Flowable 的企业级落地指南
数据库·spring boot·后端·flowable·工作流
苏三说技术3 小时前
Kafka已正式接入AI
后端
企业数字化笔记3 小时前
AI写的系统出现504怎么办?接口超时和数据库慢查询排查
数据库·后端
IT_陈寒3 小时前
Redis的Set操作居然能把我的服务整挂了?
前端·人工智能·后端
momo061173 小时前
Redis新手入门 -- 学习笔记
redis·后端
井云AI3 小时前
vendor 资源包是什么:井云 DSH 客户端打包为什么离不开它
后端·智能体小程序