为什么我需要同步 Collections.synchronizedList 返回的列表 [英] Why do I need to synchronize a list returned by Collections.synchronizedList

查看:24
本文介绍了为什么我需要同步 Collections.synchronizedList 返回的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 dos.oracle.com 上找到了这个

i found this at dos.oracle.com

public static List synchronizedList(List list)

public static List synchronizedList(List list)

返回由指定对象支持的同步(线程安全)列表列表.为了保证串行访问,至关重要的是所有对后备列表的访问是通过返回的列表完成的.用户必须手动同步返回的迭代时列出:

Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list. It is imperative that the user manually synchronize on the returned list when iterating over it:

  List list = Collections.synchronizedList(new ArrayList());
      ...
  synchronized(list) {
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }

我的问题是:如果 Collections.synchronizedList(); 应该返回一个已经同步的列表,为什么我必须同步列表来迭代它?

My question is : Why do i have to Synchronize the list to iterate it if Collections.synchronizedList(); is supposed to return an already synchronized list ?

我只是在两个线程中访问列表:一个线程只是添加,另一个线程用于获取和删除.对于这种情况,您建议使用哪些其他类?

Im just accesing the list in two threads: One Thread just add and the other thread to get and delete. What other classes you recommend to use for this scenario ?

感谢阅读.

推荐答案

列表被同步仅意味着addremove 等操作是同步的,因此是原子的.然而迭代不是,如果一个线程 adds 而另一个正在迭代,你可能会得到 ConcurrentModificationException.

The list being synchronized only means that add, remove etc. operations are synchronized and therefore atomic. Iteration however is not and if a thread adds while another is iterating, you could get a ConcurrentModificationException.

通过手动同步您的迭代块,您可以确保在迭代时不会修改列表.

By manually synchronizing your iteration block, you ensure that the list is not modified while iterating.

另一种选择是使用 a CopyOnWriteArrayList 提供了一个迭代器 迭代开始时已知的列表,不管后续的修改如何.但是,如果您需要经常更改列表的内容,则该集合不是很有效.

One alternative is to use a CopyOnWriteArrayList which provides an iterator that iterates over the list as it was known when the iteration started, regardless of subsequent modifications. That collection is however not very efficient if you need to change the content of the list very often.

这篇关于为什么我需要同步 Collections.synchronizedList 返回的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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