views:

1481

answers:

3

My question relates to this question asked earlier. In situations where I am using a queue for communication between producer and consumer threads would people generally recommend using LinkedBlockingQueue or ConcurrentLinkedQueue?

What are the advantages / disadvantages of using one over the other?

The main difference I can see from an API perspective is that a LinkedBlockingQueue can be optionally bounded.

+5  A: 

For a producer/consumer thread, I'm not sure that ConcurrentLinkedQueue is even a reasonable option - it doesn't implement BlockingQueue, which is the fundamental interface for producer/consumer queues IMO. You'd have to call poll(), wait a bit if you hadn't found anything, and then poll again etc... leading to delays when a new item comes in, and inefficiencies when it's empty (due to waking up unnecessarily from sleeps).

From the docs for BlockingQueue:

BlockingQueue implementations are designed to be used primarily for producer-consumer queues

I know it doesn't strictly say that only blocking queues should be used for producer-consumer queues, but even so...

Jon Skeet
Thanks Jon - I hadn't noticed that. So where / why would you use ConcurrentLinkedQueue?
Adamski
When you need to access the queue from a lot of threads, but you don't need to "wait" on it.
Jon Skeet
A: 

Another solution (that does not scale well) is rendezvous channels : java.util.concurrent SynchronousQueue

Loop
A: 

If your queue is non expandable and contains only one producer/consumer thread. You can use lockless queue (You don't need to lock the data access).

Rahul

Rahul