Search code examples
javamultithreadingdata-structuresconcurrencyqueue

LinkedBlockingQueue vs ConcurrentLinkedQueue


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.


Solution

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