guava-libraries:Iterators.cycle() 线程安全吗?
假设我有以下类:
public class Foo {
private List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
private Iterator<Integer> iterator = Iterators.cycle(list);
public void bar(){
Integer value = iterator.next();
doSomethingWithAnInteger(value);
}
}
如果两个线程同时访问 Foo 的实例,我需要每个线程从 iterator.next() 获取不同的值。 bar()
方法是否必须同步?或者 iterator.next() 能保证线程安全吗?
在此示例中,我使用 ArrayList 作为基础 Iterable
。循环迭代器的线程安全性是否取决于具体的可迭代实现?
Suppose I have the following class:
public class Foo {
private List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
private Iterator<Integer> iterator = Iterators.cycle(list);
public void bar(){
Integer value = iterator.next();
doSomethingWithAnInteger(value);
}
}
If an instance of Foo is acessed simultaneously by two threads, I need that each thread gets a different value from iterator.next()
. Does the bar()
method have to be made synchronized? Or is iterator.next()
guaranteed to be thread-safe?
In this example, I am using an ArrayList as the underlying Iterable
. Does the thread-safety of the cyclic iterator depend on the specific iterable implementation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Guava 中几乎没有任何东西可以保证线程安全,除非有这样的记录。
您不必同步整个 bar 方法,但应该将对 iterator.next() 的调用包装在同步块中。例如:
Pretty much nothing in Guava is guaranteed to be thread safe unless documented as such.
You do not have to synchronize the entire bar method, but you should wrap the call to iterator.next() in a synchronized block. eg:
看看 Iterators.cycle(final Iterableiterable) 的“nofollow”源代码 。即使底层 Iterator 是线程安全的,它看起来也不像循环包装器那样。这与 Java 不隐式同步迭代器的策略是一致的。
Take a look at the source code of
Iterators.cycle(final Iterable<T> iterable)
. Even if the underlying Iterator is thread-safe, it doesn't look like the cycling wrapper is. This is consistent with Java's policy of not implicitly synchronizing iterators.