In this Q&A we'll go over how to add and poll ( retrieve ) items from a queue, while also blocking if the queue is empty.
Java collections framework provides a BlockingQueue interface and multiple implementations. As the name indicates its a blocking queue class. We'll go over how to use LinkedBlockingQueue.
BlockingQueue offers three basic blocking methods
- offer() timed blocking add element method
- poll() timed blocking get element method
- take() () blocking get element method
Example below uses the poll() method.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class BlockingQueueTest {
private static LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<>();
public static void queueAdd() {
for (int i = 0; i < 1000; ++i)
lbq.add(i);
}
public static void queueReceive() {
Integer i = -1;
try {
while (i != null) {
System.out.println(i);
// blocking call
i = lbq.poll(1, TimeUnit.SECONDS);
}
} catch(InterruptedException ie ) {
throw new RuntimeException(ie.getMessage());
}
}
public static void main(String[] args ) throws InterruptedException {
ExecutorService prod = Executors.newSingleThreadExecutor();
ExecutorService consumer = Executors.newSingleThreadExecutor();
prod.submit( () -> queueAdd() );
consumer.submit( () -> queueReceive());
prod.awaitTermination(1, TimeUnit.SECONDS);
consumer.awaitTermination(1, TimeUnit.SECONDS);
prod.shutdown();
consumer.shutdown();
}
}
Comments
Post a Comment