LinkedBlockingQueue vs ConcurrentLinkedQueue

前端 未结 5 858
青春惊慌失措
青春惊慌失措 2020-12-02 03:56

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 re

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 04:28

    LinkedBlockingQueue blocks the consumer or the producer when the queue is empty or full and the respective consumer/producer thread is put to sleep. But this blocking feature comes with a cost: every put or take operation is lock contended between the producers or consumers (if many), so in scenarios with many producers/consumers the operation might be slower.

    ConcurrentLinkedQueue is not using locks, but CAS, on its put/take operations potentially reducing contention with many producer and consumer threads. But being an "wait free" data structure, ConcurrentLinkedQueue will not block when empty, meaning that the consumer will need to deal with the take() returning null values by "busy waiting", for example, with the consumer thread eating up CPU.

    So which one is "better" depends on the number of consumer threads, on the rate they consume/produce, etc. A benchmark is needed for each scenario.

    One particular use case where the ConcurrentLinkedQueue is clearly better is when producers first produce something and finish their job by placing the work in the queue and only after the consumers starts to consume, knowing that they will be done when queue is empty. (here is no concurrency between producer-consumer but only between producer-producer and consumer-consumer)

提交回复
热议问题