java BlockingQueue does not have a blocking peek?

前端 未结 8 1651
一向
一向 2020-12-15 15:37

I have a blocking queue of objects.

I want to write a thread that blocks till there is a object on the queue. Similar to the functionality provided by BlockingQueue.

8条回答
  •  执笔经年
    2020-12-15 16:36

    The quick answer is, not there's not really a way have a blocking peek, bar implementing a blocking queue with a blocking peek() yourself.

    Am I missing something?

    peek() can be troublesome with concurrency -

    • If you can't process your peek()'d message - it'll be left in the queue, unless you have multiple consumers.
    • Who is going to get that object out of the queue if you can't process it ?
    • If you have multiple consumers, you get a race condition between you peek()'ing and another thread also processing items, resulting in duplicate processing or worse.

    Sounds like you might be better off actually removing the item and process it using a Chain-of-responsibility pattern

    Edit: re: your last example: If you have only 1 consumer, you will never get rid of the object on the queue - unless it's updated in the mean time - in which case you'd better be very very careful about thread safety and probably shouldn't have put the item in the queue anyway.

提交回复
热议问题