方式将第一个元素添加到ConcurrentLinkedQueue

方式将第一个元素添加到ConcurrentLinkedQueue

本文介绍了以原子方式将第一个元素添加到ConcurrentLinkedQueue中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用方式:

I want to use a ConcurrentLinkedQueue in an atomic lock-free manner:

几个并发线程将事件推入队列,而其他线程将处理它们。队列没有绑定,我不想让任何线程等待或锁定。然而,读取部分可能注意到队列为空。在无锁实现中,读取线程不能阻塞,而只是结束其任务并继续执行其它任务(即作为ExecutorService)。因此,将第一个新事件推入空队列的作者必须知道它,并且应该重新启动阅读器(即通过向ExecutorService提交一个新的Runnable)来处理队列。

Several concurrent threads push events into the queue and some other thread will process them. The queue is not bound and I don't want any thread to wait or get locked. The reading part however may notice that the queue got empty. In a lock free implementation the reading thread must not block but will just end its task and proceeds executing other tasks (i.e. as an ExecutorService). Thus the writer pushing the first new event into an empty queue must become aware about it and should restart the reader (i.e. by submitting a new Runnable to the ExecutorService) to process the queue. Any further threads submitting a second or third event won't care about, as they may assume some reader was already prepared/submitted.

不幸的是, ConcurrentLinkedQueue的方法总是返回true。询问队列如果在添加事件之前或之后的isEmpty()将不会帮助,因为它不是原子的。
我应该使用一些额外的AtomicInteger来监控队列大小()还是有一些更聪明的解决方案?

Unfortunately the add() method of ConcurrentLinkedQueue always returns true. Asking the queue if isEmpty() before or after adding the event won't help, as it is not atomic.Should I use some additional AtomicInteger for monitoring the queue size() or is there some smarter solution for that?

Dieter。

推荐答案

使用 AtomicInteger 解决提交争用比锁或同步

Using of AtomicInteger for resolving submit contention is more efficient than locks or synchronized block.


  • 这里是。

也有。

这篇关于以原子方式将第一个元素添加到ConcurrentLinkedQueue中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:06