I have the classic problem of a thread pushing events to the incoming queue of a second thread. Only this time, I am very interested about performance. What I want to achieve is:
My first idea was to use a LinkedBlockingQueue
, but I soon realized that it is not concurrent and the performance suffered. On the other hand, I now use a ConcurrentLinkedQueue
, but still I am paying the cost of wait()
/ notify()
on each publication. Since the consumer, upon finding an empty queue, does not block, I have to synchronize and wait()
on a lock. On the other part, the producer has to get that lock and notify()
upon every single publication. The overall result is that I am paying the cost of sycnhronized (lock) {lock.notify()}
in every single publication, even when not needed.
What I guess is needed here, is a queue that is both blocking and concurrent. I imagine a push()
operation to work as in ConcurrentLinkedQueue
, with an extra notify()
to the object when the pushed element is the first in the list. Such a check I consider to already exist in the ConcurrentLinkedQueue
, as pushing requires connecting with the next element. Thus, this would be much faster than synchronizing every time on the external lock.
Is something like this available/reasonable?
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.
It belongs to java. It is used to implement Queue with the help of LinkedList concurrently. It is an unbounded thread-safe implementation of Queue which inserts elements at the tail of the Queue in a FIFO(first-in-first-out) fashion. It can be used when an unbounded Queue is shared among many threads.
A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full. A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue.
Here we have a blockingQueue that has a capacity equal to 10. It means that when a producer tries to add an element to an already full queue, depending on a method that was used to add it (offer(), add() or put()), it will block until space for inserting object becomes available. Otherwise, the operations will fail.
I think you can stick to java.util.concurrent.LinkedBlockingQueue
regardless of your doubts. It is concurrent. Though, I have no idea about its performance. Probably, other implementation of BlockingQueue
will suit you better. There's not too many of them, so make performance tests and measure.
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