Java Queues - why "poll" and "offer"?

zpangwin picture zpangwin · Feb 18, 2012 · Viewed 39.5k times · Source

Ok, so I've been using Java for a long time now and have recently been preparing for my OCJP exam. I was wondering if anyone might be able to provide any insight into why the method names "poll" (as opposed to the more traditional "pop") and "offer" (as opposed to the more traditional "push") were chosen? I'm looking specifically at the java.util.Queue interface, but would be interested in more general explanations as well :)

This is really more of an academic question than for any specific coding scenario, as I'm just trying to make sense of why Sun (as this was done before Oracle bought them) would choose to the names that they did.

Oh and before anyone decides to crucify me or throw back links to lmgtfy... I've already looked on google, yahoo, wiki, bing, and SO so if I'm overlooking some obvious search criteria or missed some old post here that explains it then I apologize in advance.

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Feb 18, 2012

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