I wonder, can anyone tell me the difference between the add and offer
methods on ConcurrentLinkedQueue? They both seem to put the specified
item on the end of the queue. That's what I want to do, so which
method do I use? Does it matter? Why are there two?
Regards,
Andrew Marlow
The Queue interface declares the two, and in the context of Queue, the
behaviors are not exactly the same. Since ConcurrentLinkedQueue
implements the Queue interface, it also has to offer both, even though for
that particular implementation, the methods can't fail due to a capacity
restriction and so the subtle difference between the two is irrelevant in
that context.
Pete
Have you considered reading the Javadocs? You should always read the
Javadocs.
<http://java.sun.com/javase/6/docs/api/java/util/Queue.html>
--
Lew
I did read the javadoc for ConcurrentLinkedQueue but I only found
minimal information there for the descriptions of add and offer. I
didn't realise the real documentation for those methods was in Queue.
But now I know. Thanks for the pointer. Here is what I found:
---
The offer method inserts an element if possible, otherwise returning
false. This differs from the Collection.add method, which can fail to
add an element only by throwing an unchecked exception. The offer
method is designed for use when failure is a normal, rather than
exceptional occurrence, for example, in fixed-capacity (or "bounded")
queues.
---
So this tells me that 'add' is what I want in this case. Thanks for
making me look more carefully at the javadocs. Being from a C++
background I am more used to doxygen than javadoc. In doxygen the
method documentation is inherited. That's why I didn't bother going to
the Queue documentation for those methods.
Regards,
Andrew Marlow
> I did read the javadoc for ConcurrentLinkedQueue but I only found
> minimal information there for the descriptions of add and offer. [...]
For future reference:
You should have noticed in the documentation for add() and offer() in
ConcurrentLinkedQueue, that those methods are "Specified by" the Queue
interface. There are even links directly to the Queue interface's own
documentation of the methods.
In other words, the connection is not as well-hidden as seems to be
implied by your description. As you spend more time using the Java SDK
documentation, these kinds of connections in the docs will probably become
more apparent to you. In the meantime, you should be actively looking for
them if you don't notice them right away.
Pete