Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Java blocking queue is most efficient for single-producer single-consumer scenarios

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 ?

like image 400
Uri Avatar asked Jun 10 '09 17:06

Uri


People also ask

How blocking queue is working What kind of problem can be solved by using blocking queue?

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.

What is blocking queue in Java?

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.

What are the different ways to solve producer-consumer problem in Java?

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.

When should we use linked blocking queue and when array blocking queue?

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.


1 Answers

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.

like image 80
Michael Myers Avatar answered Sep 25 '22 09:09

Michael Myers