我有以下代码:
public void run() {
while (true) {
m = q.poll();
if (m != null) {
kf.sendMessage(m.topic, m.message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
其中q是ConcurrentLinkedQueue.目前这是占用我100%的CPU.有没有更有效的方法来等待非阻塞队列?我更喜欢使用非阻塞队列,因为我期待来自队列中生产者的突发流量,所以我想要最大化性能.如果q.poll()返回null,有没有办法放弃对我的线程的cpu的控制?
我可以选择切换到阻塞队列,但我很好奇这样做的正确方法是什么.
编辑 - 很多好的回应!感谢你的帮助.现在我要切换到一个链接块,如果我开始遇到性能问题重新评估.
如果您没有其他事情可做,只想等待(不使用 CPU)直到数据可用,那么请使用阻塞队列。这正是它的用途,方法如下take:
检索并删除此双端队列所表示的队列的头部(换句话说,此双端队列的第一个元素),如有必要,则等待直到有元素可用。
如果您对其实现方式感兴趣,可以查看这些类的源代码,例如LinkedBlockingQueue#take:
public E take() throws InterruptedException {
E x;
int c = -1;
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
while (count.get() == 0) {
notEmpty.await();
}
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它们维护了几个条件来指示队列是否为空。