Vector vs Collections.synchronizedList(ArrayList) [英] Vector vs Collections.synchronizedList(ArrayList)

查看:21
本文介绍了Vector vs Collections.synchronizedList(ArrayList)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Vector 是同步的,ArrayList 是不同步的,但是我们可以通过 Collections.synchronizedList(aList) 来同步一个 ArrayList,那么哪个性能更好更快?

Vector is synchronized, ArrayList is not synchronized but we can synchronize an ArrayList by Collections.synchronizedList(aList), so which will perform better and faster?

推荐答案

同步集合既浪费时间又危险.为什么它们不好的一个简单例子是考虑两个线程在同一个集合上同时运行一个循环:

Synchronized collections are a waste of time and dangerous. A trivial example why they are bad is to consider two threads running a loop at the same time on the same collection:

int i = 0;
while (i < list.size())
{
  if (testSomeCondition(list.get())) {
    list.remove(i);
  else
    i++;
}

我们的列表可以同步(例如一个 Vector),但这段代码仍然会严重崩溃.为什么?因为对 size()、get()、remove() 的各个调用是同步的,但是一个线程仍然可以从列表中删除项目,而另一个正在迭代它.换句话说,我们有一个竞争条件,而使用同步集合并没有给我们带来任何好处.

Our list could be synchronized (e.g. a Vector) and this code would still break horribly. Why? Because the individual calls to size(), get(), remove(), are synchronized but one thread could still be removing items from the list while the other is iterating over it. In other words we have a race condition and the use of synchronized collections has gained us nothing.

为了解决竞争问题,我们必须同步集合上的整个操作,或者使用 Java 5 并发锁来做同样的事情.

To fix the race we have to synchronize the entire operation on the collection or use Java 5 concurrency Locks to do the same.

synchronized (list) {
  int i = 0;
  while (i < list.size())
  {
    if (testSomeCondition(list.get())) {
      list.remove(i);
    else
      i++;
  }
}

这段代码现在是线程安全的,因为一次只有一个线程可以执行循环.现在没有理由使用同步集合.我们可以使用 ArrayList 而不是 Vector 并避免所有这些同步调用的性能损失.

This block of code is now thread safe since only one thread can execute the loop at a time. And now there is no reason to use a synchronized collection. We can use an ArrayList instead of a Vector and save ourselves the performance penalty on all those synchronized calls.

所以不要使用同步集合.如果您发现自己有多个线程访问同一个列表,那么您需要保护列表上的操作,而不是单个调用.

So don't use synchronized collections. If you find yourself having multiple threads hitting the same list then you need to protect the operations on the list, not the individual calls.

这篇关于Vector vs Collections.synchronizedList(ArrayList)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆