I have a linked blocking queue in which I am performing insertion and removal operations.
I need to know which one is better put
or offer
in case of linked blocking queue.
Performance parameters are CPU utilization, memory and overall throughput.
Application usage is Real time system where there can be multiple incoming requests and less threads to handle where we will need to insert element in queue.
I read Java docs of put and offer there was not much difference in internal application.
LinkedBlockingQueue and ConcurrentLinkedQueue are the two most frequently used concurrent queues in Java. Although both queues are often used as a concurrent data structure, there are subtle characteristics and behavioral differences between them.
The LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. It means that the LinkedBlockingQueue can be bounded, if its capacity is given, else the LinkedBlockingQueue will be unbounded. The capacity can be given as a parameter to the constructor of LinkedBlockingQueue.
BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.
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.
Actually, you can't compare performance between these two, the offer
method is to just offer to the queue and it does not wait or waits for the time specified, but the put
method waits infinitely long until space is available, so their usage is different.
Use put
where you cannot afford to loose an item, keeping in mind it will hold up your call stack, otherwise use offer
.
LinkedBlockingQueue is fully reentrant and the poll() method does not block the put(). However, the poll() method will spin. You probably should be using queue.take() which waits for there to be an item in the queue instead of returning null if the queue is empty.
Also consider this scenario, poll(long, TimeUnit) method will wait for an item to be added to the queue for the time period and returns null if the timer expires. That is a cleaner wait to wait for something in the queue.
// wait for 2000ms for there to be an object in the queue
Object o = queue.poll(2000, TimeUnit.MILLISECONDS);
// no sleep necessary
return o;
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