문제

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

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top