I'm working on a standard Java system with critical timing requirements for my producers (1/100s of ms matters).
I have a producer placing stuff in a blocking queue, and a single consumer later picking up that stuff and dumping it to a file. The consumer blocks when data is not available.
Obviously, blocking queue is the appropriate interface, but which actual implementation should I choose if I want to minimize the cost to the producer? I wan to play as little as possible on things like locking and allocating when I am putting stuff in the queue, and I don't mind if the consumer has to wait a lot longer or work a lot harder.
Is there an implementation that can be faster because I only have a single consumer and single producer ?
If a producer thread tries to put an element in a full BlockingQueue, it gets blocked and stays blocked until a consumer removes an element. Similarly, if a consumer thread tries to take an element from an empty BlockingQueue, it gets blocked and remains blocked until a producer adds an element.
BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
There are many ways to solve the producer-consumer problem in Java, like you can solve this by using the wait() and notify() method, as discussed here, or you can use the Semaphore to solve this problem. In this article, you will learn a third way to solve the producer-consumer problem by using BlockingQueue in Java.
ArrayBlockingQueue is bounded which means the size will never change after its creation. LinkedBlockingQueue is optionally bounded which means it can optionally have an upper bound if desired. If no upper bound is specified, Integer.
Well, there really aren't too many options. Let me go through the listed subclasses:
DelayQueue
, LinkedBlockingDeque
, PriorityBlockingQueue
, and SynchronousQueue
are all made for special cases requiring extra functionality; they don't make sense in this scenario.
That leaves only ArrayBlockingQueue
and LinkedBlockingQueue
. If you know how to tell whether you need an ArrayList
or a LinkedList
, you can probably answer this one yourself.
Note that in LinkedBlockingQueue
, "linked nodes are dynamically created upon each insertion"; this might tend to push you toward ArrayBlockingQueue
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With