阅读 Java's ConcurrentLinkedQueue Docs ,我想知道为什么实现无法存储大小:
Beware that, unlike in most collections, the size method is NOT a constant-time operation. Because of the asynchronous nature of these queues, determining the current number of elements requires a traversal of the elements.
在哪里 the source这是“异步性质”吗?
我只看到一个 while 循环重试入队,直到 AtomicReferences 匹配预期值/引用。为什么在成功向队列提供值后无法增加 size:AtomicInteger
?
非常感谢。
最佳答案
假设您有两个线程,一个添加一个新项目,另一个删除一个项目。开始时队列中没有项目。
假设第一个线程添加项目,紧接着另一个线程删除项目并减小大小,此时您的大小为 -1,然后第一个线程将大小递增为 0。
一个稍微做作的示例,但您需要使整个操作成为原子操作,以确保没有其他线程可以访问 -1 的大小。
关于java - ConcurrentLinkedQueue 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2758966/