Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a queue to contain elements?

Tags:

java

queue

wait

I'm trying to implement a FIFO observer/observable decoupling queue, but I am not sure how to get a method to wait until a queue is not empty before returning. Here's is my current attempt but I'm sure there must a more elegant solution.

/*
 * Waits until there is data, then returns it.
 */
private Double[] get() {
    while (queue.isEmpty()) {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            // Don't care.
        }
    }

    return queue.removeFirst();
}
like image 391
Chris Cummins Avatar asked Apr 21 '12 11:04

Chris Cummins


2 Answers

Why not use a BlockingQueue - this does exactly what you want.

like image 151
Raam Avatar answered Nov 03 '22 01:11

Raam


The BlockingQueue interface has a take() method for this purpose.

like image 27
DerMike Avatar answered Nov 03 '22 00:11

DerMike