我在 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;
}
}
假设变量pass
为true
,在本地应该如何操作?
最佳答案
没有安全的方法可以做到这一点。 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.
一些集合,比如HashMap
,even can enter an infinite loop when used this way .这是 an explanation of how it happens .
你不应该这样做。没有正确的方法来做到这一点。
要么您误解了该库的工作原理,要么您需要将您的库换成由有能力的开发人员编写的库。
你用的是什么库?
关于java - 暴露不安全 ArrayList 的多线程库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17411373/