java BlockingQueue does not have a blocking peek?

前端 未结 8 1664
一向
一向 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:27

    The 'simplest' solution

    Do not process the next element until the previous element is processed succesfully.

    public void run() {
    
    Object lastSuccessfullyProcessedElement = null;
    
        while (!exit) {
            Object obj =  lastSuccessfullyProcessedElement == null ? queue.take() : lastSuccessfullyProcessedElement; // blocking
            
            boolean successful = process(obj);
            
            if(!successful) {
                lastSuccessfullyProcessedElement = obj;
            } else {
                lastSuccessfullyProcessedElement = null;
            }
        }
    }
    
    1. Calling peek() and checking if the value is null is not CPU efficient.

    I have seen CPU usage going to 10% on my system when the queue is empty for the following program.

    while (true) {
       Object o = queue.peek();
       if(o == null) continue;
       // omitted for the sake of brevity
    }
    
    1. Adding sleep() adds slowness.

    2. Adding it back to the queue using putLast will disturb the order. Moreover, it is a blocking operation which requires locks.

提交回复
热议问题