Chris Cummins
Chris Cummins

Reputation: 995

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

Upvotes: 8

Views: 8776

Answers (2)

DerMike
DerMike

Reputation: 16190

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

Upvotes: 4

Raam
Raam

Reputation: 10886

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

Upvotes: 13

Related Questions