4

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

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Essentially, only Set types return false for add.
2

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

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.