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

2019-04-21 06:58发布

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.

2条回答
Summer. ? 凉城
2楼-- · 2019-04-21 07:24

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.

查看更多
聊天终结者
3楼-- · 2019-04-21 07:37

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);
}  
查看更多
登录 后发表回答