When should I use SynchronousQueue

前端 未结 6 779
無奈伤痛
無奈伤痛 2020-12-22 17:46
new SynchronousQueue()
new LinkedBlockingQueue(1)

What is the difference? When I should use SynchronousQueue against LinkedBlock

6条回答
  •  攒了一身酷
    2020-12-22 18:23

    [Just trying to put it in (possibly) more clearer words.]

    I believe the SynchronousQueue API docs states things very clearly:

    1. A blocking queue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa.
    2. A synchronous queue does not have any internal capacity, not even a capacity of one. You cannot peek at a synchronous queue because an element is only present when you try to remove it; you cannot insert an element (using any method) unless another thread is trying to remove it; you cannot iterate as there is nothing to iterate.
    3. The head of the queue is the element that the first queued inserting thread is trying to add to the queue; if there is no such queued thread then no element is available for removal and poll() will return null.

    And BlockingQueue API docs:

    1. A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

    So the difference is obvious and somewhat critically subtle, especially the 3rd point below:

    1. If the queue is empty when you are retrieving from BlockingQueue, the operation block till the new element is inserted. Also, if the queue is full when you are inserting in the BlockingQueue, the operation will block till the element is removed from the queue and a space is made for the new queue. However note that in SynchronousQueue, as operation is blocked for opposite operation (insert and remove are opposite of each other) to occur on another thread. So, unlike BlockingQueue, the blocking depends on the existence of the operation, instead of existence or non existence of an element.
    2. As the blocking is dependent on existence of opposite operation, the element never really gets inserted in the queue. Thats why the second point: "A synchronous queue does not have any internal capacity, not even a capacity of one."
    3. As a consequence, peek() always returns null (again, check the API doc) and iterator() returns an empty iterator in which hasNext() always returns false. (API doc). However, note that the poll() method neatly retrieves and removes the head of this queue, if another thread is currently making an element available and if no such thread exists, it returns null. (API doc)

    Finally, a small note, both SynchronousQueue and LinkedBlockingQueue classes implement BlockingQueue interface.

提交回复
热议问题