Date: 2012may14
Update: 2025sep21
Language: Java
Q. Java: How can I drain a LinkedBlockingQueue?
A. Use lots of remove()'s, as shown in this full example:
import java.util.concurrent.LinkedBlockingQueue;
import java.util.NoSuchElementException;
class Demo {
static LinkedBlockingQueue<String> gQueue = new LinkedBlockingQueue<>();
static void drainQueue() {
String stuff;
for (;;) {
try {
stuff = gQueue.remove();
}
catch (NoSuchElementException ex) {
break;
}
System.out.println("processQueue: stuff=" + stuff);
}
}
public static void main(String[] args) throws InterruptedException {
gQueue.put("one");
gQueue.put("two");
gQueue.put("three");
drainQueue();
}
}
Output:
processQueue: stuff=one
processQueue: stuff=two
processQueue: stuff=three
I like this (vs. other ways) because it does what it says.
It keeps removing until there is no more.