java - 暴露不安全 ArrayList 的多线程库

标签 java multithreading

我在 Java 中使用一个返回 ArrayList 的共享库;当我遍历它时,可能会抛出一个 ConcurrentModificationException 并且我正在寻找 100%(?)保证是安全的。我正在考虑类似下面的内容,非常感谢任何意见。

data_list 是从 MT 库返回的 ArrayList<>。

boolean pass = true;

ArrayList<Something> local = new ArrayList<Something>(256);

for (int spin=0; spin<10; ++spin)
{
  try {
    local.addAll(data_list);
  }
  catch (java.util.ConcurrentModificationException ce) {
    pass = false;
  }
  finally {
    if (pass) break;
    pass = true;
  }
}

假设变量passtrue,在本地应该如何操作?

最佳答案

没有安全的方法可以做到这一点。 You should not catch ConcurrentModificationException .

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

一些集合,比如HashMapeven can enter an infinite loop when used this way .这是 an explanation of how it happens .

不应该这样做。没有正确的方法来做到这一点。

要么您误解了该库的工作原理,要么您需要将您的库换成由有能力的开发人员编写的库。

你用的是什么库?

关于java - 暴露不安全 ArrayList 的多线程库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17411373/

相关文章:

java - com.google.cloud.storage.StorageException : 401 Unauthorized (from local machine)

java - 策略模式太多 if 语句

java - spring boot 中的事务管理器和数据源 - spring data

java - HttpServletResponse - 写入响应编写器与输出流

java - 优化 CPU 上运行的最大线程数

java - 使用 CountDownLatch 和 ExecutorService 类在数据库中插入 100K 条记录

c# - 多线程C#应用程序占用了很高的CPU使用率

java - 线程 "main"java.lang.OutOfMemoryError : GC overhead limit exceeded 中 POI 的异常

JavaFX 8 JVM 退出后仍保留

使用 EJB 计时器服务的 Java 多线程