Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/9343081/java-queues-why-poll-and-offer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...