Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 630
Otavio Macedo Avatar asked Dec 20 '10 20:12

Otavio Macedo


People also ask

Are iterators thread safe?

Iterators are still not threadsafe. The solution to this iteration problem will be to acquire the collection's lock when you need to iterate over it, which we'll talk about in a future reading.

What does iterables partition do?

partition. Divides an iterable into unmodifiable sublists of the given size (the final iterable may be smaller).


1 Answers

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);
}  
like image 83
Laurence Gonsalves Avatar answered Nov 15 '22 19:11

Laurence Gonsalves