关于 LinkedBlockingQueue 与 ArrayBlockingQueue

2020-03-18 14:02:59 +08:00
 zxc1234

ArrayBlockingQueue 采用的是全局锁

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

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

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

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

1567 次点击
所在节点    程序员
5 条回复
guyeu
2020-03-18 15:23:29 +08:00
发邮件问问 Doug Lea ?
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
2020-03-18 15:57:21 +08:00
字面上看是因为 Array 没法单独操作『头』,『尾』,所以存在冲突。
zxc1234
2020-03-18 21:43:30 +08:00
@Windsooon
@rrfeng 看了一下资料,好像是这么说的
hfc
2020-03-19 09:35:19 +08:00
下面是我当时看源代码总结的,希望对你有所帮助

ArrayBlockingQueue 和 LinkedBlockingQueue 都有一个 count 域来存储队列元素个数的信息,所以两种队列的增删都会涉及到维护这个 count 值。但是在 LinkedBlockingQueue 中,count 域是 AtomicInteger 类型的,在多线程环境下也是安全的;而 ArrayBlockingQueue 的 count 域在增删时都需要进行加锁,所以只用一个可重入锁会更加方便。ArrayBlockingQueue 相比 LinkedBlockingQueue 在读写时也更加高效,LinkedBlockingQueue 相对也更需要更加细粒度的读写分离控制。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/653859

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX