Java的BlockingQueue设计问题
方法 java.util.concurrent.BlockingQueue.add(E e) 的 JavaDoc 如下:
布尔加法(E e)
将指定元素插入到 如果可以的话,这个队列 立即不违反能力 限制,返回 true 成功并抛出一个 如果没有空格则抛出 IllegalStateException 目前可用。当使用 容量受限队列,它是 通常最好使用报价。
我的问题是:它会返回 false 吗?如果不是,为什么这个方法返回一个布尔值? 我觉得很奇怪。这背后的设计决策是什么?
感谢您的知识!
曼努埃尔
the method java.util.concurrent.BlockingQueue.add(E e)'s JavaDoc reads:
boolean add(E e)
Inserts the specified element into
this queue if it is possible to do so
immediately without violating capacity
restrictions, returning true upon
success and throwing an
IllegalStateException if no space is
currently available. When using a
capacity-restricted queue, it is
generally preferable to use offer.
My question is: will it ever return false? if not, why does this method return a boolean?
It seems weird to me. What is the design decision behind this?
Thanks for your knowledge!
Manuel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它遵循
Collection.add(E e)
(因为BlockingQueue
是Collection
的子类型):It follows the contract of
Collection.add(E e)
(sinceBlockingQueue
is a subtype ofCollection
):背后的决定是:快速失败。如果队列容量有限,则会抛出 IllegalStateException。 IllegalStateException 是一个 RuntimeException。因此,如果抛出异常,则您的应用程序逻辑可能存在错误,或者您的应用程序逻辑防御性不够。或者换句话说:如果您喜欢使用有限的队列,您的应用程序应该正确处理它(使用
offer
代替)。The decision behind is: fail fast. The IllegalStateException will be thrown, if the queue has a limited capacity. IllegalStateException is a RuntimeException. So if the exception gets thrown, you probably have a fault in your application logic or your application logic is not defensive enough. Or to say it in other words: If you like to use a limited queue, your application should deal with it properly (use
offer
instead).我猜测它有一个布尔返回类型,因为它是
Queue
的子接口,它还有一个boolean add(E obj)
方法(该方法又派生自<代码>集合)。某些Queue
实现通过返回 false 来拒绝将对象添加到队列的尝试。因此,您问题的答案是 BlockingQueue 的实现永远不会返回 false。
I'm guessing it has a boolean return type because it's a subinterface of
Queue
, which also has aboolean add(E obj)
method (which in turn is derived fromCollection
). CertainQueue
implementations reject attempts to add objects to the queue by returning false.Thus, the answer to your question is that implementations of BlockingQueue will never return false.
该方法返回一个布尔值,因为它覆盖
Collection#add(E e)
。The method returns a boolean because it overrides
Collection#add(E e)
.