0

I have an ArrayBlockingQueue<String> queue; and an Author object puts elements in there:

public static final String END = "db8097f51282a0188e988d6bfa994430258e24ce";

[...]

for (String text : texts) {
            queue.put(text);
            Thread.sleep(300);
        }
queue.put(END);

and a Printer objects which takes elements from the qeue and prints them on the console:

 String text;
 do {
     text = queue.take();
     if (!text.equals(Author.END))
            System.out.println(text);
} while (tekst != Author.END);

I wanted inform Printer object that there will be no more elements put into the qeue. I cannot pass null into ArrayBlockingQueue so I decided to pass very unusual String inside. I think it is bad solution.

Can I somehow close the ArrayBlockingQueue?

Yoda
  • 17,363
  • 67
  • 204
  • 344

1 Answers1

0

your solution seems fine. Two points to consider:

  • If you're going to have more than one Printer reading values off of the same queue you may want the printer to push the END value back into the queue so that other Printers will get a chance to see it
  • Consider storing not just a plain string but instead an object of a class which you define. This class can have a string field to carry the actual payload and additional boolean field such as 'isEnd`. this will make the distinction between regular items and end-of-queue item more explicit in your code.
Itay Maman
  • 30,277
  • 10
  • 88
  • 118