问题描述
我的问题是关于synchronizedList方法Collection Class。
My question is about synchronizedList method Collections Class.
Javadocs说:
Javadocs say:
当迭代它时,用户必须在返回的列表上手动同步:
List list = Collections.synchronizedList(new ArrayList());
...
synchronized(list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
尽管手动同步不需要其他方法。我查看了集合类
的源代码,发现shyncronization已经照顾所有的方法,如添加
Though manually synchroniziation is not required for other methods. I looked into the source code of Collections classand found shyncronization has already been taken care for all methods like add
public boolean add(E e) {
synchronized(list) {return c.add(e);}
}
但不适用于迭代器方法。我认为迭代器方法也可以以同样的方式处理同步
上面的方法(它会避免额外的工作,即手动同步程序员)。我确定有
必须有一些具体的原因,但我错过了吗?
but not for iterator method. I think iterator method could have also handled synchronization in the same fashionas above method (it would have avoided the extra work i.e manual synchronization for programmers). i am sure theremust be some concrete reason behind it but i am missing it?
public Iterator<E> iterator() {
return c.iterator(); // Must be manually synched by user!
}
避免Programmer手动同步的方法 / p>
A way to avoid manual synchronization from Programmer
public Iterator<E> iterator() {
synchronized(list) {
return c.iterator(); // No need to manually synched by user!
}
}
推荐答案
't。
迭代器无法控制代码在对其上各个方法的调用之间做什么。这才是重点。您的迭代代码将重复调用 hasNext()
和 next()
这些调用是可行的,但不重要 - 重要的是,没有其他代码试图修改列表在整个迭代。
The iterator has no control over what your code does between calls to the individual methods on it. That's the point. Your iteration code will call hasNext()
and next()
repeatedly, and synchronization during those calls is feasible but irrelevant - what's important is that no other code tries to modify the list across the whole time you're iterating.
所以想象一个时间线:
t = 0: call iterator()
t = 1: call hasNext()
t = 2: call next()
// Do lots of work with the returned item
t = 10: call hasNext()
迭代器不能在t = 2时调用 next()
到 hasNext()
在t = 10。因此,如果另一个线程尝试(说)在t = 7时向列表中添加一个项目,那么迭代器如何阻止它这样做?
The iterator can't synchronize between the end of the call to next()
at t=2 and the call to hasNext()
at t=10. So if another thread tries to (say) add an item to the list at t=7, how is the iterator meant to stop it from doing so?
同步集合的总体问题:每个个体操作是同步的,而通常你想要一个完整的chunky操作同步。
This is the overall problem with synchronized collections: each individual operation is synchronized, whereas typically you want a whole chunky operation to be synchronized.
这篇关于需要手动同步同步列表而迭代时,可以避免?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!