我为什么要使用ConcurrentLinkedQueue
当我有LinkedBlockingQueue
?我知道ConcurrentLinkedQueue
是非阻塞的但是LinkedBlockingQueue
可以作为ConcurrentLinkedQueue
。我会用put()
/offer()
插入方法和poll()
去除方法。poll()
如果队列为空,方法不会等待。LinkedBlockingQueue
也是无界的。所以我可以用这个。
到目前为止我发现的区别是ConcurrentLinkedQueue
使用具有比较和交换功能的硬件级同步机制LinkedBlockingQueue
正在使用ReentrantLock
.
主要区别在于ConcurrentLinkedQueue
is 免等待,不仅仅是无锁 (有什么不同? https://en.wikipedia.org/wiki/Non-blocking_algorithm) while LinkedBlockingQueue
本质上必须保持锁定。
你可以建模ConcurrentLinkedQueue
with LinkedBlockingQueue
and poll
,但实现仍将保持锁定状态,从而减少系统的并发性。
这是一个公认的不精确的微基准测试,它检查在没有阻塞的情况下通过两个并发队列中的每一个传递 10,000 个对象的速度,并计算调用的总数poll()
在循环中:
AtomicInteger total = new AtomicInteger();
ConcurrentLinkedQueue<Integer> q = new ConcurrentLinkedQueue<>();
Thread thread = new Thread(() -> {
int remaining = 10000;
while (remaining != 0) {
total.incrementAndGet();
if (q.poll() != null) {
remaining--;
}
}
});
Integer[] first100 = new Integer[100];
for (int i = 0 ; i != 100 ; i++) {
first100[i] = i;
}
long start = System.nanoTime();
thread.start();
for (int i = 0 ; i != 10000 ; i++) {
q.add(first100[i%100]);
}
thread.join();
long runtime = System.nanoTime() - start;
这个想法是在没有其他处理的情况下测量队列的“吞吐量”。该任务在读取线程中进行了 60K 次迭代,并在 11.23 毫秒内完成(demo 1 https://ideone.com/nx4inY) with ConcurrentLinkedQueue
,以及 23,46 ms / 100K 迭代LinkedBlockingQueue
(demo 2 https://ideone.com/sYoUnO).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)