“Closing” a blocking queue

前端 未结 10 683
不思量自难忘°
不思量自难忘° 2021-01-30 09:13

I’m using java.util.concurrent.BlockingQueue in a very simple producer-consumer scenario. E.g. this pseudo code depicts the consumer part:

class QueueCo         


        
10条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 09:49

    Another idea for making this simple:

    class ComplexObject implements QueueableComplexObject
    {
        /* the meat of your complex object is here as before, just need to
         * add the following line and the "implements" clause above
         */
        @Override public ComplexObject asComplexObject() { return this; }
    }
    
    enum NullComplexObject implements QueueableComplexObject
    {
        INSTANCE;
    
        @Override public ComplexObject asComplexObject() { return null; }
    }
    
    interface QueueableComplexObject
    {
        public ComplexObject asComplexObject();
    }
    

    Then use BlockingQueue as the queue. When you wish to end the queue's processing, do queue.offer(NullComplexObject.INSTANCE). On the consumer side, do

    boolean ok = true;
    while (ok)
    {
        ComplexObject obj = queue.take().asComplexObject();
        if (obj == null)
            ok = false;
        else
            process(obj);
    }
    
    /* interrupt handling elided: implement this as you see fit,
     * depending on whether you watch to swallow interrupts or propagate them
     * as in your original post
     */
    

    No instanceof required, and you don't have to construct a fake ComplexObject which may be expensive/difficult depending on its implementation.

提交回复
热议问题