guava-libraries: is Iterators.cycle() thread-safe?

给你一囗甜甜゛ 提交于 2019-12-22 03:54:13

问题


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?

Thank you.


回答1:


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:

public void bar(){  
    Integer value;
    synchronized (iterator) {
        value = iterator.next();  
    }
    doSomethingWithAnInteger(value);
}  



回答2:


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.



来源:https://stackoverflow.com/questions/4493643/guava-libraries-is-iterators-cycle-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!