Does BlockingQueue.take() use CPU?

No…

[root@cmhlcarchapp01 ~]# cat t.java
import java.util.concurrent.*;

public class t implements Runnable {
  static ArrayBlockingQueue Q = new ArrayBlockingQueue(5);
  String type;
  public static void main (String args[]) {
    t n = new t("producer");
    t n2 = new t("consumer");
  }

  public t(String type) {
    Thread t = new Thread(this);
    this.type = type;
    t.start();
  }

  public void run() {
    try {
      if (this.type.equals("producer")) {
        for (int i = 1; i <= 10; i++) {
          t.Q.put(i);
          Thread.sleep(2000);
        }
      }
      else if (this.type.equals("consumer")) {
        for (int i = 1; i <= 10; i++) {
          System.out.println(t.Q.take());
        }
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}
[root@cmhlcarchapp01 ~]# javac t.java
Note: t.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
[root@cmhlcarchapp01 ~]# time java t
1
2
3
4
5
6
7
8
9
10

real    0m20.088s
user    0m0.088s
sys     0m0.019s
[root@cmhlcarchapp01 ~]#

You will see the following if the Queue is full and the producer can't add to it...

"Thread-0" #8 prio=5 os_prio=0 tid=0x00007f90e00f7000 nid=0x306b waiting on condition [0x00007f90c36f5000]
   java.lang.Thread.State: WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x00000000d70625e8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
        at java.util.concurrent.ArrayBlockingQueue.put(ArrayBlockingQueue.java:353)
        at t.run(t.java:25)
        at java.lang.Thread.run(Thread.java:745)

...and the following if the consumer is waiting on what is an empty queue...

"Thread-1" #9 prio=5 os_prio=0 tid=0x00007fd980101000 nid=0x35b4 waiting on condition [0x00007fd962f8d000]
   java.lang.Thread.State: WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x00000000d70625d0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
        at java.util.concurrent.ArrayBlockingQueue.take(ArrayBlockingQueue.java:403)
        at t.run(t.java:31)
        at java.lang.Thread.run(Thread.java:745)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.