LinkedBlockingQueue put vs offer

旧时模样 提交于 2019-12-04 23:19:05
Batty

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;

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.

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