Java: Maxed CPU Waiting for a Non-Blocking Queue

I have the following code:

public void run() {
    while (true) {
        m = q.poll();
        if (m != null) {
            kf.sendMessage(m.topic, m.message);
        }
    }
}

where q is ConcurrentLinkedQueue. This currently makes up 100% of my processor. Is there a more efficient way to wait in a non-blocking queue? I prefer to use a non-blocking queue because I expect packet traffic from manufacturers in the queue, so I want to maximize performance. Is there a way to give up processor control for my thread if q.poll () returns null?

I have the opportunity to switch to a blocking queue, but I am curious how to do it right.

Change - a lot of good reviews! Thank you for your help. For the moment, I'm going to just switch to the linked block, and if I start to overestimate the performance issues.

+4
4

, ( CPU) , , . , , , take:

, ( , deque), , .

, , , 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;
}

, , , .

+2

, , , .

while (true) {
    m = q.poll();
    if (m != null) {
        kf.sendMessage(m.topic, m.message);
    } else {
        // Queue was empty, wait for a little while
        // Adjust time based on your requirements
        Thread.sleep(100);
    }
}

, , , , BlockingQueue.

+1

BlockingQueue . , ,


public void run() {
    while (true) {
       m = q.take();
       kf.sendMessage(m.topic, m.message);
    }
}
0

ConcurrentLinkedQueue, - :

public void run() {
  while (true) {
    m = q.poll();
    if (m != null) {
        kf.sendMessage(m.topic, m.message);
    } else Thread.yield();
  }
}

Thread.yield. , , 50 .

0
source

Source: https://habr.com/ru/post/1538652/


All Articles