许多读者,一位作者:我需要同步吗?
当许多线程访问 get 方法而只有一个线程访问 setList 方法时,我是否需要同步这一点?
public class ListContainer {
private List<String> myList = new ArrayList<String();
public List<String> get ( )
{
return new ArrayList<String>(myList);
}
public List<String> set ( )
{
this.myList = computeList();
}
}
我不在乎读者是否得到旧数据,但数据应该是一致的。
詹宁
do i need to synchronize this, when many threads accessing the get Method and only one thread is accessing the setList method?
public class ListContainer {
private List<String> myList = new ArrayList<String();
public List<String> get ( )
{
return new ArrayList<String>(myList);
}
public List<String> set ( )
{
this.myList = computeList();
}
}
I dont care if readers get old data, but the data should be consistent.
Janning
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果满足以下条件,则不必同步(但必须将
myList
声明为易失性
):computeList
不依赖于myList
的当前状态Collections.unmodifyingList(computeList())
是表达此条件的更好方法)You don't have to synchronize (but you must declare
myList
asvolatile
) if the following conditions are true:computeList
doesn't depend on the current state ofmyList
Collections.unmodifiableList(computeList())
is the better way to express this condition)不,您不需要同步。没有任何并发修改(如果
computeList()
不依赖于myList
)。顺便说一句,为什么要返回 new ArrayList(myList) 而不是简单地返回 myList?
No, you don't need there synchronization. There are no any concurrent modifications (if
computeList()
doesnt depends on themyList
).btw, why are you returning
new ArrayList(myList)
instead of simply returnmyList
?computeList 是否依赖于 myList 并不重要,只要仅对 myList 的内容进行读取访问,就不会出现同步问题。
如果 myList 没有使用 易失性,那么即使严格设置已经替换了列表, get 也可能会返回旧的 myList。如果您不介意这种情况(它可能导致两个线程看到不同的值),那么您不需要 volatile。
It does not matter whether computeList depends on myList or not, as long as there is only reading access to the content of myList no synchronisation problem can arise.
If not using volatile for myList then it might occur that get returns the old myList, even though strictly set has already replaced the list. If you don't mind this situation (it could lead to two threads seeing different values), then you don't need volatile.
我宁愿做
HTH隐式的复制
I would rather do the copy implicit by
HTH