LinkedBlockingQueue put vs offer

安稳与你 提交于 2019-12-10 00:56:51

问题


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.


回答1:


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.




回答2:


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;



回答3:


The documentation makes the answer to this question clear. Offer doesn't wait and will "give up" if the queue has reached capacity. However, put will wait for space to become available -- in other words, it will block until space is available. Therefore offer is obviously faster since it never blocks.



来源:https://stackoverflow.com/questions/19419805/linkedblockingqueue-put-vs-offer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!