ConcurrentSkipListSet 如何具有弱一致性的迭代器?理解 'weakly consistent' 的含义

How does ConcurrentSkipListSet has Iterators that are weakly consistent? Understanding meaning of 'weakly consistent'

快速失败迭代器迭代集合。如果集合在迭代时被修改,我们会得到异常。相反适用于故障安全,迭代发生在一个集合上,而写操作发生在它的副本上,因此故障安全是如何工作的(f.e.CopyOnWriteArrayList)。

谁能解释一下 ConcurrentSkipListSet 是如何自动防故障的?修改集合时没有副本(像 CopyOnWrite 类 那样),那么它是如何发生的呢?我读是因为它的迭代器是弱一致的。我读了文档,我还是不明白。 (但我确实知道并发中的代码可见性或发生前关系是什么)。

我是初学者,有没有逻辑清晰好记的解释?

//示例:

 ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<>();
      set.add(1);
      set.add(2);
      set.add(3);
      set.add(4);

      Iterator<Integer> iterator = set.iterator();
      while (iterator.hasNext()){
          System.out.println(iterator.next());
          set.remove(4);
      }

OUTPUT:
1
2
3

我原以为会在此处抛出 ConcurrentException。请帮忙:(

“弱一致性”术语在 java.util.concurrent package description 中定义:

Most concurrent Collection implementations (including most Queues) also differ from the usual java.util conventions in that their Iterators and Spliterators provide weakly consistent rather than fast-fail traversal:

  • they may proceed concurrently with other operations
  • they will never throw ConcurrentModificationException
  • they are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction.

ConcurrentSkipListSet 的情况下,迭代器没有“fast-fail” 属性,而是反映 4 的修改已从设置。

在内部,ConcurrentSkipListSet是用ConcurrentSkipListMap实现的,它的迭代器是通过跟踪接下来应该遍历哪个跳跃列表节点来实现的。这自然会给你“弱一致性”属性:如果下一个项目被删除,迭代器仍然会return它。如果删除了下一个之后的项目,迭代器将反映这些更改。