gpt4 book ai didi

java - 正确使用 Collections.synchronizedList

转载 作者:行者123 更新时间:2023-11-29 08:34:11 24 4
gpt4 key购买 nike

我不确定如何正确使用 Collections.synchronizedList() 实现。

我有这两个:

   public synchronized static List<CurrencyBox> getOrderList() {
return Collections.synchronizedList(orderList);
}

 public static List<CurrencyBox> getOrderList() {
return Collections.synchronizedList(orderList);
}

据我所知,synchronizedList 确实返回 orderList 而不是副本,对吗?

所以如果我想保证原子操作,比如添加和删除,上面哪个实现是正确的?

Java9 有什么变化吗?或者它仍然是可行的方法,或者您有任何其他建议吗?

谢谢

最佳答案

在没有上下文的情况下很难判断,从提供的代码片段看,两者都不能保证原子操作。

文档指出:

Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.

因此,即使您同步该方法,您也将获得最好的保证,即不会有两个对象同时创建同步列表。

您需要用 Collections.synchronizedList 包装原始的 orderList 以开始并返回每次的存储结果。

private static List<CurrencyBox> orderList = Collections.synchronizedList(new ArrayList<CurrencyBox>());
public static List<CurrencyBox> getOrderList() {
return orderList
}

关于java - 正确使用 Collections.synchronizedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45567791/

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