javaconcurrencyblockingqueue

When should I use SynchronousQueue over LinkedBlockingQueue


new SynchronousQueue()
new LinkedBlockingQueue(1)

What is the difference? When I should use SynchronousQueue against LinkedBlockingQueue with capacity 1?


Solution

  • the SynchronousQueue is more of a handoff, whereas the LinkedBlockingQueue just allows a single element. The difference being that the put() call to a SynchronousQueue will not return until there is a corresponding take() call, but with a LinkedBlockingQueue of size 1, the put() call (to an empty queue) will return immediately.

    I can't say that i have ever used the SynchronousQueue directly myself, but it is the default BlockingQueue used for the Executors.newCachedThreadPool() methods. It's essentially the BlockingQueue implementation for when you don't really want a queue (you don't want to maintain any pending data).