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

查看:147
本文介绍了为什么我需要同步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 ?

感谢您阅读。

推荐答案

正在同步的列表仅表示添加删除等操作是同步的,因此是原子的。然而迭代不是,如果一个线程添加而另一个迭代,你可能会得到一个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天全站免登陆