Java – guava libraries: Yes iterators Is cycle () thread safe?
•
Java
Suppose I have the following classes:
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 accessed by two threads at the same time, I need each thread from the iterator Next () gets a different value Does the bar() method have to be synchronized? Or iterator Next() thread safe?
In this example, I use an ArrayList as the underlying Iterable Does the thread safety of loop iterators depend on the specific iterative implementation?
thank you.
Solution
There is hardly anything in guava that guarantees thread safety unless it is recorded like this
You don't have to synchronize the entire bar method, but you should wrap the call in the iterator in the synchronization block In next() For example:
public void bar(){ Integer value; synchronized (iterator) { value = iterator.next(); } doSomethingWithAnInteger(value); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码