1

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来实现线程安全集?

4

1 回答 1

1

ReadWriteLock 的需求取决于您需要实现的目标。如果要确保以原子方式更新引用,则可以使用AtomicReference(或者在您的情况下足以将此引用标记为 volatile),但是如果您的目标是更新程序线程应该等到所有读取线程完成对旧列表的迭代,然后再更新参考然后 ReadWriteLock 是要走的路。

于 2014-11-20T02:26:14.803 回答