我List
通过多个线程多次读取(迭代)但很少更新(读取次数超过 50,000 倍)。编辑:事实上,在这种情况下,一个数组就足够了,而不是一个列表。
当列表更新时,它只是用不同的版本替换(没有add()
或remove()
调用)。
CopyOnWriteArrayList避免了同步列表的缺点,但我不确定将列表设置为新值是原子的。我也读过这个问题。
显示一些代码。将以下内容视为单例 Spring bean 的属性。
List<MyObject> myList; //the list read many times and concurrently.
//called by many threads
public void doStuff(){
for (MyObject mo : myList){
//do something
}
}
//called rarely. It's synchronized to prevent concurrent updates
//but my question is about thread-safety with regards to readers
public synchronized void updateList(List<MyObject> newList){ // newList is a CopyOnWriteArrayList<>();
myList = myNewList; //is this following statement executed atomically and thread-safe for readers?
}
我是否需要使用ReadWriteLock来实现线程安全集?