[concurrency-interest] LinkedBlockingQueue and iterator question

ray hanmlw at gmail.com
Wed Oct 26 21:29:15 EDT 2005


Thanks for your reply.

If I only want to iterate the objets IN the queue(other threads may 
remove objects from the queue using the method of 
LinkedBlockingQueue.take at the same time), should I lock the queue? 
That seems too expensive. Or I can use toArray and iterate on that 
array, but also seems not better.  Other ideas?

Doug Lea wrote:

> ray wrote:
>
>> When a thread is using an iterator which point to an object in a 
>> LinkedBlockingQueue, can other threads remove this object from the 
>> queue? 
>
>
> Yes, they can. This is a property of "weakly consistent iterators"
> See
> http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.html 
>
> which says in part:
>
>    Most concurrent Collection implementations (including most Queues)
>    also differ from the usual java.util conventions in that their
>    Iterators provide weakly consistent rather than fast-fail traversal.
>    A   weakly consistent iterator is thread-safe, but does not
>    necessarily freeze the collection while iterating, so it may (or may
>    not) reflect any updates since the iterator was created.
>
> This means that an iterator need not reflect any concurrent updates
> performed since the iterator was constructed. For example, one
> legal implementation, that isn't actually used in LinkedBlockingQueue,
> is to perform toArray() on the queue upon iterator construction, and
> just iterate over that array. (The actual implementation is one
> in which you may see some additions and removals since iterator
> construction.)
>
> This is the best policy we know.
>
>
> -Doug
>


More information about the Concurrency-interest mailing list