我需要实现如下列表:
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()方法完全设置,列表没有其他变化。