guava-libraries:Iterators.cycle() 线程安全吗?

发布于 2024-10-09 02:48:16 字数 530 浏览 0 评论 0原文

假设我有以下类:

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() 能保证线程安全吗?

在此示例中,我使用 ArrayList 作为基础 Iterable。循环迭代器的线程安全性是否取决于具体的可迭代实现?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随波逐流 2024-10-16 02:48:16

Guava 中几乎没有任何东西可以保证线程安全,除非有这样的记录。

您不必同步整个 bar 方法,但应该将对 iterator.next() 的调用包装在同步块中。例如:

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

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);
}  
A君 2024-10-16 02:48:16

看看 Iterators.cycle(final Iterableiterable) 的“nofollow”源代码。即使底层 Iterator 是线程安全的,它看起来也不像循环包装器那样。这与 Java 不隐式同步迭代器的策略是一致的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文