V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
zxc1234
V2EX  ›  程序员

关于 LinkedBlockingQueue 与 ArrayBlockingQueue

  •  
  •   zxc1234 · 2020-03-18 14:02:59 +08:00 · 1562 次点击
    这是一个创建于 1500 天前的主题,其中的信息可能已经有所发展或是发生改变。

    ArrayBlockingQueue 采用的是全局锁

    LinkedBlockingQueue 在元素出队列和入队列分别分别使用不同的锁

    如果说这么做 LinkedBlockingQueue 的使用效率比较高,那么 ArrayBlockingQueue 为什么不使用两把锁

    如果说这么做 ArrayBlockingQueue 实现比较简单,那么 LinkedBlockingQueue 为什么不使用全局锁

    菜鸟看到这个知识点,不懂,求指教

    5 条回复    2020-03-19 09:35:19 +08:00
    guyeu
        1
    guyeu  
       2020-03-18 15:23:29 +08:00
    发邮件问问 Doug Lea ?
    Windsooon
        2
    Windsooon  
       2020-03-18 15:46:21 +08:00
    本质来说,是底层实现方式不同所以加锁方式不同,可以参考这里 https://stackoverflow.com/questions/11015571/arrayblockingqueue-uses-a-single-lock-for-insertion-and-removal-but-linkedblocki
    rrfeng
        3
    rrfeng  
       2020-03-18 15:57:21 +08:00
    字面上看是因为 Array 没法单独操作『头』,『尾』,所以存在冲突。
    zxc1234
        4
    zxc1234  
    OP
       2020-03-18 21:43:30 +08:00
    @Windsooon
    @rrfeng 看了一下资料,好像是这么说的
    hfc
        5
    hfc  
       2020-03-19 09:35:19 +08:00
    下面是我当时看源代码总结的,希望对你有所帮助

    ArrayBlockingQueue 和 LinkedBlockingQueue 都有一个 count 域来存储队列元素个数的信息,所以两种队列的增删都会涉及到维护这个 count 值。但是在 LinkedBlockingQueue 中,count 域是 AtomicInteger 类型的,在多线程环境下也是安全的;而 ArrayBlockingQueue 的 count 域在增删时都需要进行加锁,所以只用一个可重入锁会更加方便。ArrayBlockingQueue 相比 LinkedBlockingQueue 在读写时也更加高效,LinkedBlockingQueue 相对也更需要更加细粒度的读写分离控制。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2823 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 03:40 · PVG 11:40 · LAX 20:40 · JFK 23:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.