java - ConcurrentLinkedQueue 的大小

标签 java size queue concurrency

阅读 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/

相关文章:

java - Android AsyncTask-to-Activity 回调 nullPointerException

java - 在 MAC OS 下使用 GLFW 遇到问题

java - 从查询中获取较旧的时间戳

android - fragment - onGlobalLayout() 调用了两次

java - 如何在 View 寻呼机中找到 "last page"。或总 'number' 的 View 。安卓开发

c - 如何使用变量x来初始化数组?我知道我们不能在这里使用变量

c++ - 如何在单链表C++中找到链表的第一个值

带队列的Python线程: how to avoid to use join?

types - 在 F# 中实现队列类型

java - 将二进制值写入文件以进行霍夫曼编码