How to wait until the queue contains elements?

I am trying to implement a FIFO observer / observed interrupt queue, but I'm not sure how to make the method wait until the queue is empty before returning. Here is my current attempt, but I'm sure there should be 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();
}
+3
source share
2 answers

Why not use BlockingQueue- this is exactly what you want.

+8
source

The interface BlockingQueuehas take()for this purpose.

+3
source

All Articles