所以我坚持使用线程敌对单例实现,该实现将迭代器返回到 HashSet。 我有两个线程 - 有时 - 同时访问此 Iterator 以加载数据。我称它们为 luckyThread 和 unluckyThread。 其中一个 (unluckyThread) 抛出 ConcurrentModificationException。
问题:可以安全地假设其他线程一切正常吗? 具体来说:luckyThread 加载的数据是否没有损坏? (发生这种情况的几次,系统运行得很好,除了不幸的线程) 不要认为这个问题需要任何代码示例,但如果需要,我很乐意提供它们。
更新:(不深入细节)只要其中一个线程加载干净的数据集,系统就没问题。不用说,我解决了这个问题,但这让我开始考虑从此类异常中恢复,但我没有在网上找到任何具体的内容。
最佳答案
如果您查看 ConcurrentModificationException 的文档,它明确指出:
Note that fail-fast behavior cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.
相反,您可能应该使用一些其他机制来确保没有并发访问(例如在访问底层 HashSet 时使用 synchronized
-block 和单例)。
关于java - 从并发修改异常中恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29019035/