java - Collections.synchronizedMap(new LinkedHashMap());没有使 Map 线程安全

标签 java multithreading concurrency thread-safety

我正在使用以下构造来创建线程安全的 Map

Collections.synchronizedMap(new LinkedHashMap());

尽管我遇到了 ConcurrentModificationException 错误。

最佳答案

如果没有代码,很难猜测真正的问题是什么,但我的猜测是,您没有使用返回的集合来执行操作。根据 javadoc

In order to guarantee serial access, it is critical that all access to the backing collection is accomplished through the returned collection. It is imperative that the user manually synchronize on the returned collection when iterating over it:

  Collection c = Collections.synchronizedCollection(myCollection);
     ...
  synchronized(c) {
      Iterator i = c.iterator(); // Must be in the synchronized block
      while (i.hasNext())
         foo(i.next());
  }

不遵循此建议可能会导致不确定的行为。

关于java - Collections.synchronizedMap(new LinkedHashMap());没有使 Map 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13151166/

相关文章:

java - JShell - 防止 Enter 键执行 Java 语句或如何设置语句分隔符

iOS - 确保在主线程上执行

c# - 为什么 ReSharper 认为 "thread.Name == null"总是错误的?

java - 在单独线程上刷新 Gui

java - 如何更改 JButton 的文本颜色

java - Java String REGEX 识别 DOI 的正确格式是什么

iphone - 强制应用程序关闭并在后台运行

c++ - 宽松的原子计数器安全吗?

Java 锁条件

database - Lost Update 会发生在 PostgreSQL 的读提交隔离级别吗?