wdt_ 2020-05-30 07:58 采纳率: 0%
浏览 486

Java 非阻塞队列 ConcurrentLinkedQueue 真的是完全线程安全的吗?

为什么在 size 方法里面没有加锁,这样在统计的时候不会被其他线程干扰吗?

public int size() {
    int count = 0;
    // first()获取第一个具有非空元素的节点,若不存在,返回null
    // succ(p)方法获取p的后继节点,若p==p,next,则返回head,表示回到头部重新开始找
    for (Node<E> p = first(); p != null; p = succ(p))
    if (p.item != null)
    if (++count == Integer.MAX_VALUE)
        break;
    return count;
}
  • 写回答

1条回答 默认 最新

  • 毕小宝 博客专家认证 2020-05-30 08:43
    关注

    据JDK 介绍,这个类是无界线程安全的链表队列,这个 size 方法在并发应用中是不准确的:

    /**
         * Returns the number of elements in this queue.  If this queue
         * contains more than {@code Integer.MAX_VALUE} elements, returns
         * {@code Integer.MAX_VALUE}.
         *
         * <p>Beware that, unlike in most collections, this method is
         * <em>NOT</em> a constant-time operation. Because of the
         * asynchronous nature of these queues, determining the current
         * number of elements requires an O(n) traversal.
         * Additionally, if elements are added or removed during execution
         * of this method, the returned result may be inaccurate.  Thus,
         * this method is typically not very useful in concurrent
         * applications.
         *
         * @return the number of elements in this queue
         */
    
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序