java - 为什么要同步同步列表?

标签 java collections concurrency

<分区>

如果我创建这样一个列表:

List<MyObj> myobjs = Collections.synchronizedList(new ArrayList<MyObj>()); 

相关文档声称此返回列表需要同步才能遍历元素。然而,我可以同步一个常规列表并用同步块(synchronized block)保护它。那么,为什么我需要一个“synchronizedList”?

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.

It is imperative that the user manually synchronize on the returned list when iterating over it:

  List list = Collections.synchronizedList(new ArrayList());
      ...
  synchronized (list) {
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }

Failure to follow this advice may result in non-deterministic behavior. The returned list will be serializable if the specified list is serializable.

Parameters: list the list to be "wrapped" in a synchronized list. Returns: a synchronized view of the specified list.

最佳答案

synchronizedList 是一个方便的包装器,它允许您在大多数情况下避免手动同步,但在对其进行迭代时则不然。

对于普通的非同步列表,如果它被多个线程使用,您将需要始终手动同步,因此使用 synchronizedList 会很方便。

需要synchronizedList 的情况可能是,如果您将列表传递给某些不在列表上同步的第三方代码,但您仍然需要同步。但是,这很容易出错,因为您会依赖第三方代码不会遍历列表或使用其他非原子操作的事实,因此最好尽可能完全避免这种情况(例如,通过复制列表)。

关于java - 为什么要同步同步列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28373729/

相关文章:

java - JPQL构造函数执行需要很长时间

java - 为多模块微服务 Spring Boot 应用程序设置 swagger 文档

java - 过滤数组中的差异

java - BoundedSemaphore 信号量与标准互斥量

c++ - 我使用 OpenMP 的线程越多,执行时间就越长,这是怎么回事?

java - Netty:回调在哪里?

java - map nasted 在集合中。获取 2D map 的 value() 集

c# - 如何在 C# 中创建涉及集合的单元测试?

delphi - 自上而下迭代通用集合(TDictionary)

java - 当其他线程可以访问它时从数据库更新静态映射