When should I use SynchronousQueue

前端 未结 6 793
無奈伤痛
無奈伤痛 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:13

    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.

提交回复
热议问题