Alex Rivera | Logout

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

Asked 2012-02-18T16:50:39.480
50

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.

Edit
Report

2 Answers

58

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

answered 2012-02-18T16:57:07.157
2

I assume it's simply because the names push and pop sound ambiguous between the behavior of add and remove and that of offer and poll — and pop, in particular, is reminiscent of java.util.Stack.pop(), which behaves like remove rather than like poll. The names add and remove were obviously chosen to match the names of similar methods elsewhere in the Java Collections Framework, which either perform the requested operation or else raise an exception; the names offer and poll are suggestive of the fact that they don't raise exceptions.

answered 2012-02-18T16:58:42.840

Your Answer