小编eri*_*iee的帖子

线程安全读取并实例化列表

我需要实现如下列表:

private List<Foo> list = new ArrayList<>();

public synchronized Foo getFoo(Condition condition) {
    // loop the list and get a foo that meets the condition
    for (Foo foo: list) {
        if(condition.check(foo)) {
            return foo;
        }
    }
    return null;
}

public synchronized void refresh() {
    list = new ArrayList<>(fetchFromDB());
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来避免同步方法以使读取和实例化线程安全?我认为 CopyOnWriteArrayList 在这里没有帮助,因为同一个列表上没有变异操作,而且每次我们只是创建一个新列表。我对吗?


更新:澄清一下,该列表只能通过refresh()方法完全设置,列表没有其他变化。

java concurrency list thread-safety

5
推荐指数
1
解决办法
132
查看次数

标签 统计

concurrency ×1

java ×1

list ×1

thread-safety ×1