Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 478
Anton Avatar asked Dec 21 '11 14:12

Anton


People also ask

What is the use of LinkedBlockingQueue?

The LinkedBlockingQueue uses linked lists as its internal storage. It is considered as a thread-safe collection. Hence, it is generally used in multi-threading applications. Suppose, one thread is inserting elements to the queue and another thread is removing elements from the queue.

What is SynchronousQueue?

SynchronousQueue is a special blocking queue with no internal capacity. It helps in exchange data or information between threads in a thread-safe manner.

Is LinkedBlockingQueue thread-safe?

BlockingQueue implementations like ArrayBlockingQueue, LinkedBlockingQueue are thread-safe. All queuing methods use internal locks or other forms of concurrency control to achieve their effects atomically.


2 Answers

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

like image 56
jtahlborn Avatar answered Oct 03 '22 17:10

jtahlborn


As far as I understand code above do the same things.

No, the code is not the same at all.

Sync.Q. requires to have waiter(s) for offer to succeed. LBQ will keep the item and offer will finish immediately even if there is no waiter.

SyncQ is useful for tasks handoff. Imagine you have a list w/ pending task and 3 threads available waiting on the queue, try offer() with 1/4 of the list if not accepted the thread can run the task on its own. [the last 1/4 should be handled by the current thread, if you wonder why 1/4 and not 1/3]

Think of trying to hand the task to a worker, if none is available you have an option to execute the task on your own (or throw an exception). On the contrary w/ LBQ, leaving the task in the queue doesn't guarantee any execution.

Note: the case w/ consumers and publishers is the same, i.e. the publisher may block and wait for consumers but after offer or poll returns, it ensures the task/element is to be handled.

like image 45
3 revs Avatar answered Oct 03 '22 19:10

3 revs