Java Queues – why “poll” and “offer”?

Because these methods have different semantics explained in the JavaDoc. add/remove are unconditional while offer/poll return special value:

  • offer only offers a new value, but it might not be accepted, e.g. if the queue is full

  • poll only polls for the value, but we accept the fact the value might not be there.

To complicate matters more, BlockingQueue introduces yet another pair of methods for blocking add/remove. Of course they could have used the same named with a bunch of parameters/flags,

smellyGet(boolean blocking, boolean failOnEmpty)

but don’t you think this is a better design?

        | Throws ex. | Special v. | Blocks | Times out
--------+------------+------------+--------+---------------------
Insert  | add(e)     | offer(e)   | put(e) | offer(e, time, unit)
Remove  | remove()   | poll()     | take() | poll(time, unit)
Examine | element()  | peek()     | N/A    | N/A

* https://meta.stackexchange.com/questions/73566

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)