开发者

Java's BlockingQueue design question

开发者 https://www.devze.com 2023-01-25 01:31 出处:网络
the method java.util.concurrent.BlockingQueue.add(E e)\'s JavaDoc reads: boolean add(E e) Inserts the specified element into

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开发者_如何学C 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


It follows the contract of Collection.add(E e) (since BlockingQueue is a subtype of Collection):

If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.


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).


I'm guessing it has a boolean return type because it's a subinterface of Queue, which also has a boolean add(E obj) method (which in turn is derived from Collection). Certain Queue 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.


The method returns a boolean because it overrides Collection#add(E e).

0

精彩评论

暂无评论...
验证码 换一张
取 消