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

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

问题描述

矢量是同步的,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天全站免登陆