Vector浅析

Vector与ArrayList很像,主要区别在于Vector是线程安全的。

Vector的类声明:

*

As of the Java 2 platform v1.2, this class was retrofitted to
* implement the {@link List} interface, making it a member of the
*
* Java Collections Framework
. Unlike the new collection
* implementations, {@code Vector} is synchronized. If a thread-safe
* implementation is not needed, it is recommended to use {@link
* ArrayList} in place of {@code Vector}.

阅读源码后发现,Vector是通过给所有的外部类加上synchronized来实现线程安全的。这种实现方式很简单,但由于synchronized是对this加锁,所以当需要同时一个对象的多个方法时,效率就会很低。

另外,查看iterator的源码

/**
 * Returns an iterator over the elements in this list in proper sequence.
 *
 * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 *
 * @return an iterator over the elements in this list in proper sequence
 */
public synchronized Iterator<E> iterator() {
    return new Itr();
}

可以发现,在返回遍历对象后,就已经退出了锁,如果修改了对象之后,再去遍历,则会抛出ConcurrentModificationException异常.

Vector<String> vector = new Vector<String>();
vector.add("abc");
Iterator<String> ite = vector.iterator();
vector.add("bcd");
while (ite.hasNext()) {
    System.out.println(ite.next());
}

运行结果:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.Vector$Itr.checkForComodification(Vector.java:1184)
    at java.util.Vector$Itr.next(Vector.java:1137)
    at com.showstone.containerresearch.list.VectorResearch.main(VectorResearch.java:14)