Search code examples
javaqueuewait

How to wait for a queue to contain elements?


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();
}

Solution

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