需要手动同步同步列表而迭代时,可以避免? [英] Need to manually synchronize the Synchronized list while iteration when it could be avoided?

查看:360
本文介绍了需要手动同步同步列表而迭代时,可以避免?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于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 class and 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 fashion as above method (it would have avoided the extra work i.e manual synchronization for programmers). i am sure there must 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!
   }
}


推荐答案


我认为迭代器方法也可以采用与上述方法相同的方式处理同步。

I think iterator method could have also handled synchronization in the same fashion as above method

'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.

这篇关于需要手动同步同步列表而迭代时,可以避免?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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