Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java LinkedBlockingQueue with ability to signal when done?

I have a situation of a single producer and single consumer working with a queue of objects. There are two situations when the queue might be empty:

  1. The consumer handled the objects quicker than the producer was capable of generating new objects (producer uses I/O before generating objects).
  2. The producer is done generating objects.

If the queue is empty, I want the consumer to wait until a new object is available or until the producer signals that it is done.

My research so far got me no where because I still ended up with a loop that checks both the queue and a separate boolean flag (isDone). Given that there's no way of waiting on multiple locks (thought of waiting on the queue AND the flag), what can be done to solve this?

like image 903
Yon Avatar asked Mar 03 '12 07:03

Yon


1 Answers

First of all, the suggestion that using a wrapper is "too much overhead" is a guess, and IMO a very bad one. This assumption should be measured with a performance test with actual requirements. If and only if the test fails, then verify using a profiler that wrapping the queue object is why.

Still if you do that and wrapping the queue object (in this case a String) really is the cause of unacceptable performance, then you can use this technique: create a known, unique string to serve as an "end of messages" message.

    public static final String NO_MORE_MESSAGES = UUID.randomUUID().toString();

Then when retrieving Strings from the queue, just check (it can be an reference check) if the String is NO_MORE_MESSAGES. If so, then you're done processing.

like image 111
Sean Reilly Avatar answered Sep 27 '22 17:09

Sean Reilly