矢量VS Collections.synchronizedList(ArrayList中) [英] Vector vs Collections.synchronizedList(ArrayList)

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

问题描述

Vector是同步的,但ArrayList是不同步的,但我们可以通过Collections.synchronizedList(ALIST)同步一个ArrayList,所以这将有更好的表现和更快

Vector is synchronized but 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++;
}

我们的列表可以同步(例如一个向量),这code仍然打破可怕。为什么?因为个人调用尺寸(),得到(),删除(),是同步的,但一个线程仍可能,而另一个遍历其从列表中删除的项。换句话说,我们有一个竞争条件和使用同步收藏已经获得了我们什么都没有。

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++;
  }
}

code的此块现在是线程安全的,因为只有一个线程可以同时执行循环。现在还没有理由使用同步的集合。我们可以用一个ArrayList代替矢量和拯救自己在所有这些同步调用的性能损失。

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.

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

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