番石榴库:Iterators.cycle()线程安全吗? [英] guava-libraries: is Iterators.cycle() thread-safe?
问题描述
假设我有以下课程:
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()
是线程安全的?
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?
在此示例中,我使用ArrayList作为基础Iterable.循环迭代器的线程安全性是否取决于特定的可迭代实现?
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?
谢谢.
推荐答案
除非有相关说明,否则Guava中几乎没有任何东西可以保证线程安全.
Pretty much nothing in Guava is guaranteed to be thread safe unless documented as such.
您不必同步整个bar方法,但应将对iterator.next()的调用包装在一个同步块中.例如:
You do not have to synchronize the entire bar method, but you should wrap the call to iterator.next() in a synchronized block. eg:
public void bar(){
Integer value;
synchronized (iterator) {
value = iterator.next();
}
doSomethingWithAnInteger(value);
}
这篇关于番石榴库:Iterators.cycle()线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!