gpt4 book ai didi

java - 许多读者,一个作家 : Do i need to synchronize this?

转载 作者:搜寻专家 更新时间:2023-11-01 02:18:10 25 4
gpt4 key购买 nike

当许多线程访问 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();
}
}

我不在乎读者是否得到旧数据,但数据应该是一致的。

詹宁

最佳答案

如果满足以下条件,则不必同步(但必须将 myList 声明为 volatile):

  • computeList 不依赖于 myList
  • 的当前状态
  • 分配列表后不要更改列表的内容(Collections.unmodifiableList(computeList()) 是表达这种情况的更好方式)

关于java - 许多读者,一个作家 : Do i need to synchronize this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2312430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com