Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedBlockingQueue put vs offer

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.

like image 687
Scientist Avatar asked Oct 17 '13 06:10

Scientist


People also ask

Is LinkedBlockingQueue concurrent?

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.

What is the use of LinkedBlockingQueue in Java?

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.

Is blocking queue thread safe?

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.

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.


2 Answers

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.

like image 122
codingenious Avatar answered Oct 02 '22 17:10

codingenious


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;
like image 21
Dark Knight Avatar answered Oct 02 '22 17:10

Dark Knight