[concurrency-interest] LinkedBlockingQueue and iterator question

David Holmes dholmes at dltech.com.au
Wed Oct 26 21:52:31 EDT 2005


Ray,

> 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?

You can't "lock" the queue. There is no single lock that protects access to
the queue - this is a concurrent data structure that supports concurrent put
and take operations.

I'm not clear what your requirements are. You say you want to iterate
objects IN the queue, but at the same time you are allowing the queue to be
modified concurrently - these conflict. You cannot guarantee that an item
returned by the iterator (or through an entry in toArray()) is still in
queue at the time you access it - you only know that it was in the queue.

If you need to exclude access to the queue while iterating you need a
higher-level protocol to provide that in your application. The simplest way
to get such a protocol is to not use a concurrent data structure like
LinkedBlockingQueue but, for example, a synchronizedList wrapping a
LinkedList.

What you need to do really depends on your exact requirements.

Cheers,
David Holmes



More information about the Concurrency-interest mailing list